1
0
mirror of https://github.com/TeamNewPipe/NewPipe synced 2026-01-13 18:22:41 +00:00

Compare commits

..

861 Commits

Author SHA1 Message Date
9290ed490f Translated using Weblate (Turkish)
Currently translated at 100.0% (164 of 164 strings)
2017-04-21 11:12:23 +02:00
monolifed
1bda812c75 Translated using Weblate (Turkish)
Currently translated at 100.0% (164 of 164 strings)
2017-04-21 11:11:23 +02:00
Weblate
ab82406c98 Merge remote-tracking branch 'origin/master' 2017-04-19 17:36:17 +02:00
Mladen Pejaković
be763349df Translated using Weblate (Serbian)
Currently translated at 99.3% (163 of 164 strings)
2017-04-19 17:36:16 +02:00
zmni
91764ad601 Translated using Weblate (Indonesian)
Currently translated at 100.0% (164 of 164 strings)
2017-04-19 17:36:14 +02:00
Christian Schabesberger
1c4031aa38 Merge branch 'master' of github.com:theScrabi/NewPipe 2017-04-18 22:39:16 +02:00
Christian Schabesberger
c3bc648dd4 moved on to version 0.9.3 2017-04-18 22:34:32 +02:00
Christian Schabesberger
c97d794272 updated sdk and support lib 2017-04-18 22:34:04 +02:00
Christian Schabesberger
8e7d2e91e9 Merge branch 'feature-backplayer' of https://github.com/mauriciocolli/NewPipe into mark 2017-04-18 22:06:47 +02:00
Laura Arjona Reina
cf0fbbbd3d Translated using Weblate (Spanish)
Currently translated at 100.0% (164 of 164 strings)
2017-04-18 20:19:12 +02:00
Tobias Groza
7d3ede7946 Translated using Weblate (German)
Currently translated at 100.0% (164 of 164 strings)
2017-04-18 12:58:44 +02:00
Eduardo Caron
1aa308eb5d Translated using Weblate (Portuguese (Brazil))
Currently translated at 100.0% (164 of 164 strings)
2017-04-18 00:35:02 +02:00
4bfd30e34a Translated using Weblate (Portuguese (Brazil))
Currently translated at 99.3% (163 of 164 strings)
2017-04-18 00:28:43 +02:00
Eduardo Caron
0f46c90688 Translated using Weblate (Portuguese (Brazil))
Currently translated at 99.3% (163 of 164 strings)
2017-04-18 00:27:31 +02:00
Matej U
aa2173fc4a Translated using Weblate (Slovenian)
Currently translated at 100.0% (164 of 164 strings)
2017-04-17 18:09:10 +02:00
Mauricio Colli
932cb1d19c Remove ugly bitmap sharing and improvements
- Now it is just using the ImageLoader to load the image, and better yet, it already have cache implemented in it
- Improve MainActivity intent handler
- Improve utils classes
2017-04-17 01:21:48 -03:00
Mauricio Colli
18b038d8e4 Improve notification layouts 2017-04-17 01:20:14 -03:00
Mauricio Colli
2ac71c75c0 Improve players
- Background player is using ExoPlayer internally now
2017-04-17 01:19:53 -03:00
naofum
4067ba5232 Translated using Weblate (Japanese)
Currently translated at 100.0% (164 of 164 strings)
2017-04-16 16:48:37 +02:00
Marian Hanzel
ab47dd5a5b Translated using Weblate (Slovak)
Currently translated at 100.0% (164 of 164 strings)
2017-04-15 22:32:17 +02:00
Nathan Follens
3130910307 Translated using Weblate (Dutch)
Currently translated at 100.0% (164 of 164 strings)
2017-04-15 17:35:12 +02:00
Sérgio Marques
22113439a4 Translated using Weblate (Portuguese)
Currently translated at 100.0% (164 of 164 strings)
2017-04-15 16:09:58 +02:00
Weblate
2d25a9ad7a Merge remote-tracking branch 'origin/master' 2017-04-15 16:07:22 +02:00
Freddy Morán Jr
8f0a2cc2f0 Translated using Weblate (Spanish)
Currently translated at 100.0% (161 of 161 strings)
2017-04-15 16:07:22 +02:00
Marian Hanzel
4ca39258c9 Translated using Weblate (Slovak)
Currently translated at 100.0% (161 of 161 strings)
2017-04-15 16:07:21 +02:00
Enol P
d0c0238b8b Translated using Weblate (Asturian)
Currently translated at 98.1% (158 of 161 strings)
2017-04-15 16:07:20 +02:00
Sérgio Marques
f9f08e5169 Translated using Weblate (Portuguese)
Currently translated at 100.0% (161 of 161 strings)
2017-04-15 16:07:18 +02:00
Christian Schabesberger
cfc51b2401 Merge branch 'master' of github.com:theScrabi/NewPipe 2017-04-15 14:05:39 +02:00
Christian Schabesberger
54c2704cb5 switch to dark default theme 2017-04-15 14:05:31 +02:00
Christian Schabesberger
9b51c946fe add 1080p to available features 2017-04-15 13:43:21 +02:00
Christian Schabesberger
06f38cbcb4 Merge branch 'feature-4k60f' of git://github.com/mauriciocolli/NewPipe into 4k 2017-04-15 12:52:03 +02:00
Christian Schabesberger
f368d6b257 update extractor 2017-04-15 12:51:35 +02:00
Marian Hanzel
f4301da14d Translated using Weblate (Slovak)
Currently translated at 100.0% (161 of 161 strings)
2017-04-13 21:49:26 +02:00
Weblate
f34c09f165 Merge remote-tracking branch 'origin/master' 2017-04-13 20:51:06 +02:00
Freddy Morán Jr
6d1db56512 Translated using Weblate (Spanish)
Currently translated at 100.0% (161 of 161 strings)
2017-04-13 20:51:03 +02:00
Christian Schabesberger
b70c07d004 update extractor 2017-04-13 19:41:43 +02:00
Christian Schabesberger
f9f48a5eb6 Merge branch 'master' of github.com:theScrabi/NewPipe 2017-04-13 19:41:28 +02:00
Christian Schabesberger
14e4e73444 update gradle 2017-04-13 19:41:15 +02:00
Nathan Follens
f2ce4d2daf Translated using Weblate (Dutch)
Currently translated at 100.0% (161 of 161 strings)
2017-04-13 19:10:56 +02:00
naofum
468ebdda87 Translated using Weblate (Japanese)
Currently translated at 100.0% (161 of 161 strings)
2017-04-13 16:53:26 +02:00
nautilusx
a1f0fb3b14 Translated using Weblate (German)
Currently translated at 100.0% (161 of 161 strings)
2017-04-13 16:08:34 +02:00
zmni
3c9f4de234 Translated using Weblate (Indonesian)
Currently translated at 100.0% (161 of 161 strings)
2017-04-13 15:59:13 +02:00
Tobias Groza
8ae411619f Translated using Weblate (German)
Currently translated at 96.8% (156 of 161 strings)
2017-04-13 15:56:35 +02:00
nautilusx
61e5c9121a Translated using Weblate (German)
Currently translated at 96.2% (155 of 161 strings)
2017-04-13 15:55:28 +02:00
Weblate
8a3cf0d5dc Merge remote-tracking branch 'origin/master' 2017-04-13 15:53:52 +02:00
Freddy Morán Jr
ecb5df65ac Translated using Weblate (Spanish)
Currently translated at 100.0% (160 of 160 strings)
2017-04-13 15:53:52 +02:00
5f1e98a0d3 Translated using Weblate (German)
Currently translated at 96.2% (154 of 160 strings)
2017-04-13 15:53:49 +02:00
Mauricio Colli
3b9a477499 Add resolution support up to 4k and 60 fps
- Up to 4k with 60 fps
    - Not every device can play in that resolution and bitrate
    - Add option to hide these high resolution greater than 1080p (2k,4k) for not clutter the menus
- Add a default resolution for the popup, wil be used when opening in popup mode from another app
2017-04-12 03:07:15 -03:00
Christian Schabesberger
e5bf98a741 move on to version 0.9.2 2017-04-11 22:51:04 +02:00
Christian Schabesberger
06fafc247e move to version 0.9.2 of NewPipeExtractor 2017-04-11 22:49:18 +02:00
Christian Schabesberger
e8bb17b631 Merge branch 'fix-next-video' of git://github.com/mauriciocolli/NewPipe into mul 2017-04-11 22:26:41 +02:00
Freddy Morán Jr
363cd07883 Translated using Weblate (Spanish)
Currently translated at 100.0% (160 of 160 strings)
2017-04-11 18:56:03 +02:00
Mladen Pejaković
2b4a9286c4 Translated using Weblate (Serbian)
Currently translated at 99.3% (159 of 160 strings)
2017-04-11 00:46:21 +02:00
Nathan Follens
34c985026f Translated using Weblate (Dutch)
Currently translated at 100.0% (160 of 160 strings)
2017-04-10 17:40:52 +02:00
naofum
4a0aa42914 Translated using Weblate (Japanese)
Currently translated at 100.0% (160 of 160 strings)
2017-04-10 17:21:54 +02:00
Mauricio Colli
746c2a15bf Migrate to fragments and improvements
- Migrate to fragments
- Fix #487
- Don't show "Open in popup mode" to channel links
- New backstack of videos
- Change the subscribers count to format using `NumberFormat`, for example some locales use `.`  others `,`, this handles it automatically (and the old method had a bug for leading zero, e.g. 4.82.125 instead of 4.082.125)
- Add string 'subscribers' for channels with more than 1 subscriber (plural)
- Popup player chooses the default format and resolution based on the new preference (format)
- Fix taskaffinity of the router activities
- Show title before loading, as it is available from the items already loaded
2017-04-09 14:34:00 -03:00
zmni
9318bb5306 Translated using Weblate (Indonesian)
Currently translated at 100.0% (160 of 160 strings)
2017-04-09 07:39:53 +02:00
Matej U
2a10ceb74f Translated using Weblate (Slovenian)
Currently translated at 100.0% (160 of 160 strings)
2017-04-08 22:08:31 +02:00
Weblate
83f4db59e2 Merge remote-tracking branch 'origin/master' 2017-04-08 21:47:50 +02:00
Olexandr Nesterenko
9f66f759ad Translated using Weblate (Ukrainian)
Currently translated at 84.9% (135 of 159 strings)
2017-04-08 21:47:47 +02:00
Christian Schabesberger
6f015349e8 moved on to v0.9.1 2017-04-08 17:17:58 +02:00
Christian Schabesberger
a37802c2b9 add prefered video format 2017-04-08 17:17:11 +02:00
Florian
4fa3baf5e1 Translated using Weblate (French)
Currently translated at 99.3% (158 of 159 strings)
2017-04-07 12:45:03 +02:00
Oscar Hemelaar
ef8c2c81d5 Translated using Weblate (Italian)
Currently translated at 98.7% (157 of 159 strings)
2017-04-07 03:45:31 +02:00
Mladen Pejaković
8c80d8c457 Translated using Weblate (Serbian)
Currently translated at 99.3% (158 of 159 strings)
2017-04-07 00:46:25 +02:00
Matej U
1596872c54 Translated using Weblate (Slovenian)
Currently translated at 100.0% (159 of 159 strings)
2017-04-05 14:47:22 +02:00
Oscar Hemelaar
da8873fa78 Translated using Weblate (French)
Currently translated at 99.3% (158 of 159 strings)
2017-04-05 12:14:32 +02:00
Oscar Hemelaar
ecd8439b3f Translated using Weblate (French)
Currently translated at 98.1% (156 of 159 strings)

if it's for a video restart button, it's "Relancer"
2017-04-05 02:53:08 +02:00
Oscar Hemelaar
5d178532ac Translated using Weblate (French)
Currently translated at 97.4% (155 of 159 strings)
2017-04-05 02:52:24 +02:00
Oscar Hemelaar
08e40a013d Translated using Weblate (French)
Currently translated at 96.8% (154 of 159 strings)

or "OK" ?
2017-04-05 02:50:49 +02:00
Oscar Hemelaar
c136f7363c Translated using Weblate (French)
Currently translated at 96.2% (153 of 159 strings)
2017-04-05 02:50:26 +02:00
Florian
a60f10d739 Translated using Weblate (French)
Currently translated at 90.5% (144 of 159 strings)
2017-04-04 21:45:44 +02:00
naofum
ae46afcb42 Translated using Weblate (Japanese)
Currently translated at 100.0% (159 of 159 strings)
2017-04-04 16:15:27 +02:00
mueller-ma
bffb9f6800 Translated using Weblate (German)
Currently translated at 95.5% (152 of 159 strings)
2017-04-03 09:29:35 +02:00
Tobias Groza
79aa9ad04b Translated using Weblate (German)
Currently translated at 94.9% (151 of 159 strings)
2017-04-03 09:26:41 +02:00
ff5714f04a Translated using Weblate (French)
Currently translated at 89.9% (143 of 159 strings)
2017-04-02 18:59:25 +02:00
zmni
ce499a9766 Translated using Weblate (Indonesian)
Currently translated at 100.0% (159 of 159 strings)
2017-04-02 16:49:33 +02:00
Weblate
d3bb8b7651 Merge remote-tracking branch 'origin/master' 2017-04-02 16:48:37 +02:00
Freddy Morán Jr
6d9c23c4cb Translated using Weblate (Spanish)
Currently translated at 100.0% (158 of 158 strings)
2017-04-02 16:48:36 +02:00
Nathan Follens
b95a9332a9 Translated using Weblate (Dutch)
Currently translated at 100.0% (158 of 158 strings)
2017-04-02 16:48:35 +02:00
zmni
609715eb5c Translated using Weblate (Indonesian)
Currently translated at 100.0% (158 of 158 strings)
2017-04-02 16:48:33 +02:00
Christian Schabesberger
a1266c919c Merge branch 'fix-next-video' of git://github.com/mauriciocolli/NewPipe into strfx 2017-04-02 15:56:41 +02:00
Christian Schabesberger
a1925a0302 Merge branch 'master' of github.com:theScrabi/NewPipe 2017-04-02 15:48:53 +02:00
Christian Schabesberger
a7a4c03372 update features list, and moved on to v0.9.0 2017-04-02 15:47:21 +02:00
Christian Schabesberger
37201600e0 Merge pull request #494 from mueller-ma/patch-1
Fix list in readme
2017-04-02 15:44:14 +02:00
mueller-ma
a94f40ed62 Fix list in readme 2017-04-02 14:33:52 +02:00
naofum
0b08cf8c76 Translated using Weblate (Japanese)
Currently translated at 100.0% (158 of 158 strings)
2017-04-01 13:36:04 +02:00
Mauricio Colli
33e29be7db Fix next video and refactor
- Refactor VideoItemDetailActivity, StreamExtractorWorker
- Remove redundant styles
- Change dimensions
- Nicer animation/transitions
2017-03-31 20:39:54 -03:00
Freddy Morán Jr
bd1c7851c7 Translated using Weblate (Portuguese)
Currently translated at 100.0% (158 of 158 strings)
2017-04-01 01:02:49 +02:00
Freddy Morán Jr
82faea5965 Translated using Weblate (Spanish)
Currently translated at 100.0% (158 of 158 strings)
2017-04-01 00:51:34 +02:00
Weblate
0bbbfd3217 Merge remote-tracking branch 'origin/master' 2017-04-01 00:44:52 +02:00
Freddy Morán Jr
fb578ecda8 Translated using Weblate (Spanish)
Currently translated at 100.0% (156 of 156 strings)
2017-04-01 00:44:41 +02:00
Christian Schabesberger
e804647a65 make exoplayer default player 2017-03-29 09:17:03 +02:00
Christian Schabesberger
c3c3a94593 Merge branch 'feature-popup-fullscreen' of git://github.com/mauriciocolli/NewPipe into toogle 2017-03-29 08:48:00 +02:00
Mauricio Colli
9d55569f80 Fix keep screen on 2017-03-28 09:12:03 -03:00
Christian Schabesberger
5dd8271c15 Merge pull request #489 from mauriciocolli/master
Fix travis and some clean-up
2017-03-27 23:53:04 +02:00
Mauricio Colli
7a4a54c3ea Fix travis
- Remove duplicate of AndroidManifest
- Remove some non-translatable strings from "ar" translation, and general clean-up of other
2017-03-27 16:34:37 -03:00
Mauricio Colli
7c9078a625 Fix non-commited file 2017-03-27 11:26:36 -03:00
Mauricio Colli
71ae342f52 Implement screen orientation toggle 2017-03-27 10:12:22 -03:00
Mauricio Colli
b43c56085d Implement fullscreen and quality selector
- Implement cache
- Abstract player
- Quality selector
- Fullscreen switcher
- Change some drawables
2017-03-27 01:08:16 -03:00
Christian Schabesberger
83d2ab95e0 Merge branch 'master' of github.com:TeamNewPipe/NewPipe 2017-03-26 17:29:25 +02:00
Christian Schabesberger
20a8d7372c fix broken overlay on .svg icon 2017-03-26 17:29:16 +02:00
Weblate
c36ba88db7 Merge remote-tracking branch 'origin/master' 2017-03-25 14:05:16 +01:00
Nathan Follens
4aa23023ee Translated using Weblate (Dutch)
Currently translated at 100.0% (156 of 156 strings)
2017-03-25 14:05:13 +01:00
Christian Schabesberger
8735cf931a update to new backend with playlist support 2017-03-22 20:14:56 +01:00
Weblate
2473069326 Merge remote-tracking branch 'origin/master' 2017-03-21 09:44:34 +01:00
vesp
03bab57a97 Translated using Weblate (Czech)
Currently translated at 99.3% (155 of 156 strings)
2017-03-21 09:44:32 +01:00
Christian Schabesberger
e3baf69533 fix channel rotation problem 2017-03-17 20:35:22 +01:00
Christian Schabesberger
461f747af1 add IOException 2017-03-17 20:18:44 +01:00
Christian Schabesberger
028872a7d8 Merge pull request #483 from mauriciocolli/patch-2
Fix bug when fetching unavailable content
2017-03-17 17:10:03 +01:00
Christian Schabesberger
a1483b6c55 Merge pull request #481 from mauriciocolli/patch-1
Handle embed links
2017-03-17 17:09:13 +01:00
mauriciocolli
e406ba094c Improve bug detection
- Show a message with the appropriate error (network error)
2017-03-17 12:09:20 -03:00
mauriciocolli
c100d15ba8 Fix bug when fetching unavailable content
- Fix #482
- When opening a invalid/deleted/unavailable video, the popup was just printing the error, now it shows a message to the user and exits
2017-03-17 11:50:27 -03:00
mauriciocolli
b4ea592638 Handle embed links
- Fix #480
- Add /embed/ to intent filter, as the app already handles these type of links internally
2017-03-17 00:27:59 -03:00
Sérgio Marques
16b757d9a3 Translated using Weblate (Portuguese)
Currently translated at 100.0% (156 of 156 strings)
2017-03-17 00:46:17 +01:00
Sérgio Marques
2aa801a392 Translated using Weblate (Portuguese)
Currently translated at 100.0% (156 of 156 strings)
2017-03-14 23:24:24 +01:00
Matej U
b838344526 Translated using Weblate (Slovenian)
Currently translated at 100.0% (156 of 156 strings)
2017-03-13 10:30:41 +01:00
zmni
233a3df222 Translated using Weblate (Indonesian)
Currently translated at 100.0% (156 of 156 strings)
2017-03-11 13:27:00 +01:00
naofum
da6661b1ea Translated using Weblate (Japanese)
Currently translated at 100.0% (156 of 156 strings)
2017-03-11 12:37:49 +01:00
Mladen Pejaković
c6e120fc51 Translated using Weblate (Serbian)
Currently translated at 100.0% (156 of 156 strings)
2017-03-10 23:09:42 +01:00
Marian Hanzel
c416a1254d Translated using Weblate (Slovak)
Currently translated at 100.0% (156 of 156 strings)
2017-03-10 23:07:10 +01:00
Weblate
2aa4f6ddda Merge remote-tracking branch 'origin/master' 2017-03-10 21:45:11 +01:00
Enrico Monese
129597023d Translated using Weblate (Italian)
Currently translated at 100.0% (154 of 154 strings)
2017-03-10 21:45:10 +01:00
vesp
02aed86b7e Translated using Weblate (Czech)
Currently translated at 98.7% (152 of 154 strings)
2017-03-10 21:45:10 +01:00
Tobias Groza
e44f4b5823 Translated using Weblate (German)
Currently translated at 98.7% (152 of 154 strings)
2017-03-10 21:45:08 +01:00
Christian Schabesberger
2f0c0f0fc2 Merge branch 'master' of github.com:TeamNewPipe/NewPipe 2017-03-09 16:21:36 +01:00
Christian Schabesberger
e5ce3f3007 moved on to version 0.8.12 2017-03-09 16:21:20 +01:00
Christian Schabesberger
095a2be748 change popuplayer class description 2017-03-09 16:14:49 +01:00
Christian Schabesberger
c75fe88757 Merge branch 'feature-popup' of git://github.com/mauriciocolli/NewPipe 2017-03-09 16:08:33 +01:00
Christian Schabesberger
a8ff4b0744 Fix backbutton behaviour
- close on MainActivity when back pressed
- clear NavStack on rotation
2017-03-09 16:01:09 +01:00
Christian Schabesberger
c02c511e31 Update .travis.yml
update build-tools version for travis
2017-03-09 15:41:10 +01:00
Mauricio Colli
b9550fb528 Merge remote-tracking branch 'upstream/master' into feature-popup 2017-03-09 04:49:15 -03:00
Mauricio Colli
a37d8f083a Implement popup mode
- Add icons replay, fast_forward
- Add strings
- Add menu entry
- Add as option to open link directly to popup mode
2017-03-09 04:42:40 -03:00
Mauricio Colli
abff1f537b Add ExoMedia and remove ExoPlayer
- Remove ExoPlayer files
- Added ExoMedia library
2017-03-09 01:44:00 -03:00
Enrico Monese
483fde5e42 Translated using Weblate (Italian)
Currently translated at 100.0% (154 of 154 strings)
2017-03-08 23:52:45 +01:00
Weblate
761b7ea57b Merge remote-tracking branch 'origin/master' 2017-03-07 18:45:34 +01:00
zmni
af92631a0c Translated using Weblate (Indonesian)
Currently translated at 100.0% (154 of 154 strings)
2017-03-07 18:45:29 +01:00
Christian Schabesberger
ffe832d061 update gradle verson 2017-03-07 14:14:02 +01:00
Christian Schabesberger
a08cbfcef1 Merge branch 'master' of github.com:TeamNewPipe/NewPipe 2017-03-06 15:36:13 +01:00
Christian Schabesberger
d2d6ac1bf8 add CCC slides 2017-03-06 15:36:04 +01:00
Weblate
615ffca64b Merge remote-tracking branch 'origin/master' 2017-03-05 16:35:55 +01:00
Tobias Groza
2fcf6197c5 Translated using Weblate (German)
Currently translated at 97.4% (150 of 154 strings)
2017-03-05 16:35:54 +01:00
zmni
22d31ae14f Translated using Weblate (Indonesian)
Currently translated at 100.0% (154 of 154 strings)
2017-03-05 16:35:52 +01:00
Christian Schabesberger
8c786e121b get down to support lib 25.1.0 2017-03-04 13:30:21 +01:00
Christian Schabesberger
99d2a33c8c reset support lib to 25.1.1
25.2.0 is not yet supported by fdroid
2017-03-04 13:23:54 +01:00
Marian Hanzel
010a24db3f Translated using Weblate (Slovak)
Currently translated at 100.0% (154 of 154 strings)
2017-03-04 10:57:28 +01:00
Weblate
9408da453b Merge remote-tracking branch 'origin/master' 2017-03-02 15:26:33 +01:00
Jose Maeso
dbda4202fd Translated using Weblate (Spanish)
Currently translated at 98.7% (152 of 154 strings)
2017-03-02 15:26:32 +01:00
Mladen Pejaković
5776e91459 Translated using Weblate (Serbian)
Currently translated at 100.0% (154 of 154 strings)
2017-03-02 15:26:32 +01:00
Matej U
664d7b69b1 Translated using Weblate (Slovenian)
Currently translated at 100.0% (154 of 154 strings)
2017-03-02 15:26:30 +01:00
Christian Schabesberger
6b9140c60d make extractor sub use https 2017-03-01 19:25:19 +01:00
Christian Schabesberger
383857d110 add extractor submodule 2017-03-01 19:08:12 +01:00
Christian Schabesberger
cffd049c8a remove extractor 2017-03-01 19:06:27 +01:00
Christian Schabesberger
ecabc65e94 Merge branch 'master' of github.com:TeamNewPipe/NewPipe 2017-03-01 18:03:50 +01:00
Christian Schabesberger
780f1d5da3 made extractor systemindipendent again 2017-03-01 18:03:36 +01:00
naofum
e2d0fc34a3 Translated using Weblate (Japanese)
Currently translated at 100.0% (154 of 154 strings)
2017-03-01 17:41:48 +01:00
Christian Schabesberger
3404231457 get rid of xul xml parser 2017-03-01 16:40:04 +01:00
Mladen Pejaković
b17928570d Translated using Weblate (Serbian)
Currently translated at 100.0% (154 of 154 strings)
2017-03-01 14:15:48 +01:00
Weblate
8ed86261ef Merge remote-tracking branch 'origin/master' 2017-03-01 12:45:58 +01:00
RACER
a313b91a0a Translated using Weblate (Japanese)
Currently translated at 100.0% (149 of 149 strings)
2017-03-01 12:45:45 +01:00
Christian Schabesberger
7b6dae20be add loading footer to search fragment 2017-02-28 13:24:07 +01:00
Christian Schabesberger
552c70bb0d add adblocker for youtube red stuff 2017-02-28 13:05:20 +01:00
Christian Schabesberger
8f734737f0 fix bug and add footer cycle to channel 2017-02-28 12:13:29 +01:00
Christian Schabesberger
800e7bcb7a moved on to v0.8.11 2017-02-27 21:37:22 +01:00
Christian Schabesberger
2002234d86 fix channel load more videos error 2017-02-27 21:31:20 +01:00
Christian Schabesberger
5923663e08 add routed_intent activity 2017-02-27 21:14:03 +01:00
Christian Schabesberger
4cdf20ab8c fix differences 2017-02-27 19:21:41 +01:00
Christian Schabesberger
af65a1cfef Merge branch 'feature-theme-change' of git://github.com/mauriciocolli/NewPipe into conf 2017-02-27 19:04:38 +01:00
Christian Schabesberger
927057ab83 Merge pull request #465 from mauriciocolli/fix-travis
Fix travis and YoutubeStreamUrlIdHandler
2017-02-27 19:03:28 +01:00
Christian Schabesberger
ffbc001ad5 fix navstack channel problem 2017-02-27 19:00:06 +01:00
Christian Schabesberger
f5625a1151 fix dashmpd bug 2017-02-27 17:57:16 +01:00
Christian Schabesberger
ce2ceb8a1b fix layout 2017-02-27 16:38:01 +01:00
Christian Schabesberger
c14771534f redesign channel activity 2017-02-27 15:58:09 +01:00
59436419
553cec16d5 Removed old icons 2017-02-27 17:30:47 +05:30
59436419
d17496f720 Improved code for changing theme 2017-02-27 17:25:15 +05:30
Christian Schabesberger
89e70626eb update support framework 2017-02-26 21:38:02 +01:00
Mauricio Colli
2ccae841d6 Change variable names
For a better understanding of what is going on
2017-02-26 07:47:13 -03:00
Mauricio Colli
07f6d0f149 Fix bug lower case id
This method was passing the lowercase url
2017-02-25 18:15:50 -03:00
Mauricio Colli
319d769233 Change video Id
The previous wasn't working
2017-02-25 18:14:32 -03:00
Mauricio Colli
6ec393699e Check if selected theme it's not the current 2017-02-25 16:04:10 -03:00
Mauricio Colli
f8d9e0fa60 Implement restart dialog 2017-02-25 15:36:31 -03:00
Mauricio Colli
50ed962a82 Add necessary strings 2017-02-25 15:34:45 -03:00
Christian Schabesberger
8654705e9b Change T to K 2017-02-22 12:12:39 +01:00
Weblate
b79ed8185f Merge remote-tracking branch 'origin/master' 2017-02-21 17:48:35 +01:00
Rom1
0d6c67f64f Translated using Weblate (French)
Currently translated at 96.6% (144 of 149 strings)
2017-02-21 17:48:34 +01:00
Marian Hanzel
e97a6569a6 Translated using Weblate (Slovak)
Currently translated at 100.0% (149 of 149 strings)
2017-02-21 17:48:32 +01:00
Christian Schabesberger
d0d41c6b16 move on to v0.8.10 2017-02-19 16:09:39 +01:00
Christian Schabesberger
f7a531e71b Merge branch 'fix_nav' 2017-02-19 16:09:02 +01:00
Christian Schabesberger
c28fddc4dd did some finetuning 2017-02-19 16:07:45 +01:00
zmni
b6ea10fc73 Translated using Weblate (Indonesian)
Currently translated at 100.0% (149 of 149 strings)
2017-02-19 15:45:16 +01:00
Gian Maria Viglianti
320eb44061 Translated using Weblate (Italian)
Currently translated at 100.0% (149 of 149 strings)
2017-02-19 00:54:12 +01:00
Christian Schabesberger
7a6b5dd5b7 add initial support for NavStack 2017-02-18 21:59:48 +01:00
naofum
460653ed16 Translated using Weblate (Japanese)
Currently translated at 100.0% (149 of 149 strings)
2017-02-17 16:18:49 +01:00
Mladen Pejaković
b6fda788c5 Translated using Weblate (Serbian)
Currently translated at 100.0% (149 of 149 strings)
2017-02-16 22:12:17 +01:00
Matej U
da4b9306fa Translated using Weblate (Slovenian)
Currently translated at 100.0% (149 of 149 strings)
2017-02-16 22:00:25 +01:00
Weblate
d76c02cbf4 Merge remote-tracking branch 'origin/master' 2017-02-16 21:44:49 +01:00
nonamebg
4d5466b5cd Translated using Weblate (English)
Currently translated at 100.0% (141 of 141 strings)
2017-02-16 21:44:40 +01:00
Christian Schabesberger
e9c20ac8b0 add search channels to available features 2017-02-16 13:57:48 +01:00
Christian Schabesberger
961820a250 Merge branch 'search_channel' 2017-02-16 13:33:46 +01:00
Christian Schabesberger
4cc2976061 add unit test for new channel search 2017-02-16 00:46:15 +01:00
Christian Schabesberger
477f182b43 convert android tests to junit tests 2017-02-16 00:17:43 +01:00
Christian Schabesberger
a5252bb765 add search filter menu 2017-02-15 15:21:36 +01:00
Christian Schabesberger
3f0078f38a git channel item running 2017-02-15 12:59:36 +01:00
Christian Schabesberger
91434dd2ac setup core for search channel support 2017-02-13 00:55:11 +01:00
Christian Schabesberger
f29bd0a6e7 fix actionbar icon theming 2017-02-12 16:45:01 +01:00
Christian Schabesberger
7186f58374 remove StreamInfoItemSearchCollector 2017-02-12 14:22:39 +01:00
Christian Schabesberger
5c8bcf15ba make colector hirarchicall
remove broken commit()
2017-02-12 13:39:39 +01:00
Christian Schabesberger
130757ee99 Update CONTRIBUTING.md 2017-02-12 00:16:41 +01:00
Christian Schabesberger
5020a4f9dc add mailinglist to contributing 2017-02-11 22:26:00 +01:00
Christian Schabesberger
ef15902ec4 add InfoItem 2017-02-11 21:33:01 +01:00
zmni
ed8d13f837 Translated using Weblate (Indonesian)
Currently translated at 100.0% (141 of 141 strings)
2017-02-11 19:20:01 +01:00
ksyko
c2fcae7c43 Merge pull request #1 from TeamNewPipe/master
0.8.9 update
2017-02-11 23:21:58 +05:30
aladar42
27f2c65e6d Translated using Weblate (Czech)
Currently translated at 100.0% (141 of 141 strings)
2017-02-10 18:44:38 +01:00
Weblate
0b3428ede9 Merge remote-tracking branch 'origin/master' 2017-02-08 17:13:21 +01:00
aladar42
3e0102ad2a Translated using Weblate (Czech)
Currently translated at 100.0% (141 of 141 strings)
2017-02-08 17:13:19 +01:00
Christian Schabesberger
c42002ccc5 removed download notice again 2017-02-06 00:04:20 +01:00
Christian Schabesberger
e8101d5d91 change download link 2017-02-05 23:56:26 +01:00
Christian Schabesberger
ecdf4ad502 add np download to readme 2017-02-05 21:09:36 +01:00
Matej U
af760f9cdc Translated using Weblate (Slovenian)
Currently translated at 100.0% (141 of 141 strings)
2017-02-05 20:16:33 +01:00
Weblate
b3491da49f Merge remote-tracking branch 'origin/master' 2017-02-05 12:46:26 +01:00
Snob Malkowitch
c322feeaff Translated using Weblate (Russian)
Currently translated at 94.3% (134 of 142 strings)
2017-02-05 12:46:18 +01:00
Christian Schabesberger
b26f46a063 Merge pull request #439 from marcobiscaro2112/master
Adding brazilian portuguese translation
2017-02-03 12:37:22 +01:00
Christian Schabesberger
9f0944dc5a Merge pull request #441 from k3b/master
fix NullPointerExcpeption when opening "Downloads" with android-api < 23
2017-02-03 12:35:52 +01:00
k3b
e869098434 fix NullPointerExcpeption when opening "Downloads" with android-api < 23 2017-02-02 01:58:47 +01:00
Weblate
4baa23af5f Merge remote-tracking branch 'origin/master' 2017-02-01 20:58:21 +01:00
aladar42
78fc5bbbd5 Translated using Weblate (Czech)
Currently translated at 97.1% (138 of 142 strings)
2017-02-01 20:58:20 +01:00
Wiredframe
a69784d168 Translated using Weblate (German)
Currently translated at 100.0% (142 of 142 strings)
2017-02-01 20:58:11 +01:00
Marco Biscaro
d48a7f1a18 Adding brazilian portuguese translation
(Also set settings_keys as untranslatable)
2017-02-01 12:32:06 -02:00
Christian Schabesberger
082c6128ad moved on to 0.8.9 2017-01-31 18:28:47 +01:00
Christian Schabesberger
7c9771873b Merge branch 'master' of git://github.com/ksyko/NewPipe into jf 2017-01-31 18:25:30 +01:00
Christian Schabesberger
7257cdacc8 fix background button problem 2017-01-31 18:23:22 +01:00
Christian Schabesberger
140b480f82 url signature fix
* fixed stacktrace
* changed player url
* took regex fix from youtube-dl

final fix taken from youtube-dl
2017-01-31 18:06:44 +01:00
Christian Schabesberger
77db2f8a48 update support Framework 2017-01-31 10:58:53 +01:00
naofum
22bc81b0eb Translated using Weblate (Japanese)
Currently translated at 100.0% (142 of 142 strings)
2017-01-27 15:50:44 +01:00
Mladen Pejaković
b52b3d4be0 Translated using Weblate (Serbian)
Currently translated at 100.0% (142 of 142 strings)
2017-01-26 18:49:26 +01:00
Nathan Follens
f845098b42 Translated using Weblate (Dutch)
Currently translated at 100.0% (142 of 142 strings)
2017-01-26 16:48:57 +01:00
Weblate
0f7397e3b8 Merge remote-tracking branch 'origin/master' 2017-01-26 15:46:09 +01:00
Shaye Faletha
0b9d99fdc9 Translated using Weblate (Polish)
Currently translated at 99.2% (140 of 141 strings)
2017-01-26 15:46:06 +01:00
59436419
9a1da5cc75 Made changes for ICS and JB 2017-01-26 12:07:41 +05:30
Christian Schabesberger
9e76f94cf6 update support lib and move on to 0.8.8 2017-01-22 14:47:05 +01:00
Christian Schabesberger
7d6b92e064 Merge branch 'feature-improve-search-fragment' of git://github.com/coffeemakr/NewPipe into cofe 2017-01-22 14:42:36 +01:00
Christian Schabesberger
849a45a3ca resolve conflict 2017-01-22 14:26:01 +01:00
Christian Schabesberger
7ddea5a71b Merge branch 'feature-accept-embed-links' of git://github.com/coffeemakr/NewPipe into url 2017-01-22 13:55:53 +01:00
Christian Schabesberger
5d81358c15 rename Themer to ThemableActivity 2017-01-22 13:48:50 +01:00
Christian Schabesberger
492aad9d70 Merge branch 'master' of git://github.com/ksyko/NewPipe into kyko 2017-01-22 13:32:39 +01:00
Weblate
647cfcd401 Merge remote-tracking branch 'origin/master' 2017-01-21 15:44:14 +01:00
Yann Hodiesne
c60d98e52d Translated using Weblate (French)
Currently translated at 97.1% (137 of 141 strings)
2017-01-21 15:44:14 +01:00
Osoitz
d3cfac6b15 Translated using Weblate (Basque)
Currently translated at 37.5% (53 of 141 strings)
2017-01-21 15:44:11 +01:00
Coffeemakr
7fb4e5a143 Rename download db sqlite file
Rename the sqlite database to "downloads.db" instead of "newpipe.db"
to make sure the file will create a conflicts later.
2017-01-20 18:57:30 +01:00
Coffeemakr
8e451b2a83 Use fragments setHasOptionsMenu
Remove complications by allowing android to handle fragment's
options menu.

See https://developer.android.com/guide/components/fragments.html#ActionBar
2017-01-19 19:39:33 +01:00
ksyko
8083f06fe7 Update SettingsFragment.java 2017-01-18 00:12:36 +05:30
59436419
44521a2e56 Added dark theme 2017-01-17 22:35:23 +05:30
59436419
dfeed3d0eb Added dark theme 2017-01-17 22:31:00 +05:30
59436419
081a45b70d Added dark theme 2017-01-17 22:13:33 +05:30
59436419
616a721bba Added dark theme 2017-01-17 21:43:30 +05:30
59436419
c9aa553b32 Added dark theme 2017-01-17 20:54:00 +05:30
59436419
e3d59c3cff Added dark theme 2017-01-17 20:47:12 +05:30
59436419
df51635674 Added dark theme 2017-01-17 20:33:54 +05:30
59436419
1e81f61760 Added dark theme 2017-01-17 20:31:14 +05:30
59436419
a4043eab83 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	app/src/main/java/org/schabi/newpipe/Themer.java
#	app/src/main/java/org/schabi/newpipe/download/DownloadActivity.java
#	app/src/main/java/org/schabi/newpipe/settings/SettingsActivity.java
#	app/src/main/res/layout-v18/fragment_videoitem_detail.xml
#	app/src/main/res/layout/fragment_videoitem_detail.xml
#	app/src/main/res/xml/settings.xml
2017-01-17 16:18:00 +05:30
59436419
60dc19d2bc Added Dark Theme 2017-01-17 16:13:14 +05:30
ksyko
a2e4585fe8 Update InfoItemHolder.java 2017-01-17 16:13:02 +05:30
ksyko
b5df281447 Update fragment_videoitem_detail.xml 2017-01-17 16:13:02 +05:30
ksyko
650917f9f9 Update fragment_videoitem_detail.xml 2017-01-17 16:13:02 +05:30
ksyko
3a9c95a9ae Update fragment_videoitem_detail.xml 2017-01-17 16:13:01 +05:30
59436419
5458acfcad Added dark theme 2017-01-17 16:13:01 +05:30
59436419
68e80e6054 Added dark theme 2017-01-17 16:13:01 +05:30
Christian Schabesberger
e4aa69b8d3 add some super.function() thingies 2017-01-16 16:06:54 +01:00
Coffeemakr
dfd40e43da Fix for #407 2017-01-16 13:01:52 +01:00
Coffeemakr
7efd111d9c Improve Search fragment
* Keep search query when fragment is restored
 * Simplify SuggestionListAdapter
   * Use ResourceCursorAdapter for view creation
 * Fix deprecation warning
 * Some clean code
2017-01-16 07:33:58 +01:00
Matej U
6809172203 Translated using Weblate (Slovenian)
Currently translated at 99.2% (140 of 141 strings)
2017-01-15 12:46:28 +01:00
Coffeemaker
40a4343f06 Translated using Weblate (German)
Currently translated at 98.5% (139 of 141 strings)
2017-01-13 18:45:02 +01:00
Matej U
cd9333b39e Translated using Weblate (Slovenian)
Currently translated at 98.5% (139 of 141 strings)
2017-01-12 21:46:19 +01:00
Mladen Pejaković
82d426c781 Translated using Weblate (Serbian)
Currently translated at 100.0% (141 of 141 strings)
2017-01-12 21:46:11 +01:00
YFdyh000
c7e773de25 Translated using Weblate (Chinese (Simplified))
Currently translated at 98.5% (139 of 141 strings)
2017-01-12 18:44:21 +01:00
Coffeemakr
2ded33110f Improve YoutubeStreamUrlIdHandler
* Make it a singelton
 * Accept embed links
 * Accept share links (youtube.com/shared?ci=...)
 * Add tests
 * Accept host case insensititve
2017-01-11 17:25:53 +01:00
zmni
b26c0aa9da Translated using Weblate (Indonesian)
Currently translated at 100.0% (141 of 141 strings)
2017-01-11 16:51:32 +01:00
Mladen Pejaković
2fc8fb6f17 Translated using Weblate (Serbian)
Currently translated at 100.0% (141 of 141 strings)
2017-01-10 21:08:24 +01:00
Coffeemakr
ea76f1d6e2 Improve DownloadManager and -Service
* Fix permission at some places
 * Fix access problem for downloaded files with external player
 * Store finished Downloads
 * Remove binding to DownloadService just to download a file
 * Javadoc
 * Code improvements
2017-01-10 17:48:55 +01:00
naofum
7cda1d116b Translated using Weblate (Japanese)
Currently translated at 100.0% (141 of 141 strings)
2017-01-10 17:03:28 +01:00
Weblate
8bf7a1a9db Merge remote-tracking branch 'origin/master' 2017-01-10 17:02:24 +01:00
naofum
0aa0ad65c0 Translated using Weblate (Japanese)
Currently translated at 100.0% (140 of 140 strings)
2017-01-10 17:02:21 +01:00
Coffeemakr
53ff58daa3 DownloadManagerService: Don't bind if no permissions 2017-01-10 13:35:16 +01:00
Christian Schabesberger
b3225bebe6 fix recaptch weblate conflict 2017-01-09 22:46:07 +01:00
Allan Nordhøy
4beafad71f Translated using Weblate (Norwegian Bokmål)
Currently translated at 92.8% (130 of 140 strings)
2017-01-09 21:45:13 +01:00
Allan Nordhøy
c96f933626 Translated using Weblate (English)
Currently translated at 100.0% (140 of 140 strings)
2017-01-09 21:45:12 +01:00
LNJ
bea6359d5f Translated using Weblate (German)
Currently translated at 99.2% (139 of 140 strings)
2017-01-09 21:45:04 +01:00
Christian Schabesberger
92db9cb59b update support lib and move on to 0.8.7 2017-01-04 17:20:01 +01:00
Benoît Mauduit
410c4ca736 Remove old comment 2017-01-03 14:38:22 +01:00
Benoît Mauduit
80c9dbf180 Cosmetic 2017-01-03 14:38:22 +01:00
Benoît Mauduit
c9edac2820 Change the way to start reCaptchaActivity
* Use startActivityForResult() and onActivityResult() to refresh the
  search request when returning from reCaptcha activity.
2017-01-03 14:38:22 +01:00
Benoît Mauduit
143df9a529 Start reCaptcha activity when starting video directly 2017-01-03 14:38:22 +01:00
Benoît Mauduit
c87da9903f Set result code and finish() Activity instead of starting MainActivity
* Activities will start reCaptchaActivity with startActivityForResult and
look for RECAPTCHA_REQUEST and RESULT_OK | RESULT_CANCELED in : 'onActivityResult()'
2017-01-03 14:38:22 +01:00
Andi Saputro
0f69e6c64d Translated using Weblate (Indonesian)
Currently translated at 100.0% (140 of 140 strings)
2016-12-31 18:45:16 +01:00
ksyko
1b9a6e53ce Update InfoItemHolder.java 2016-12-31 22:32:16 +05:30
ksyko
c7abf377eb Update fragment_videoitem_detail.xml 2016-12-31 21:51:41 +05:30
ksyko
175d8ce572 Update fragment_videoitem_detail.xml 2016-12-31 21:43:01 +05:30
ksyko
1708a401cf Update fragment_videoitem_detail.xml 2016-12-31 21:42:04 +05:30
59436419
141278e668 Added dark theme 2016-12-31 13:46:52 +05:30
59436419
754bd82699 Added dark theme 2016-12-30 01:07:27 +05:30
andideveloper
999efb6660 Translated using Weblate (Indonesian)
Currently translated at 100.0% (140 of 140 strings)
2016-12-29 17:25:23 +01:00
Weblate
0b391a9ef3 Merge remote-tracking branch 'origin/master' 2016-12-28 12:46:32 +01:00
naofum
2a99ac4430 Translated using Weblate (Japanese)
Currently translated at 100.0% (140 of 140 strings)
2016-12-28 12:46:22 +01:00
Christian Schabesberger
a5589d0865 Merge branch 'feature-background-progress' of git://github.com/coffeemakr/NewPipe into coffeemakr-feature-background-progress 2016-12-28 10:46:38 +01:00
Coffeemakr
83541a0d5d Add 8dp margin on the right side of the progress bar 2016-12-28 08:15:12 +01:00
Coffeemakr
ac0dff7aa1 Make shure thread quits before service 2016-12-27 16:17:59 +01:00
Coffeemakr
f22b5157f5 Notify thread on play/pause 2016-12-27 15:58:17 +01:00
Coffeemakr
659d0d6115 Add PlaybackState broadcast messages
They can be used to retrieve the current playback
 * Duration
 * Played time
 * If the media player is playing
2016-12-27 15:52:02 +01:00
Marian Hanzel
fd8c99fd8d Translated using Weblate (Slovak)
Currently translated at 100.0% (140 of 140 strings)
2016-12-27 15:47:58 +01:00
Coffeemakr
9494f3a299 Add progress bar to expanded notification 2016-12-27 14:49:59 +01:00
Coffeemakr
8021848b03 Remove note field completly
Always use noteBuilder directly to generate a notification
2016-12-27 14:41:30 +01:00
Coffeemakr
5a127c26e6 Improve notification building/updateing
* Use custom notification builder which has methods to set the artist
  and title and also a method to set the playing state
* Update builder instead of view -> resovles deprecated warnings
2016-12-27 14:37:18 +01:00
Coffeemakr
a7d734c20c Ignore vim's temporary files 2016-12-27 13:32:03 +01:00
Coffeemakr
7c7129f9a1 Notifications: Set customs views in builder 2016-12-27 13:31:34 +01:00
Coffeemakr
05cbc7891d Typos corrected in StreamInfo 2016-12-27 13:26:48 +01:00
Coffeemakr
14623456ff Correct typos 2016-12-27 13:19:12 +01:00
Coffeemakr
5064ec3ac4 Fix spelling 2016-12-27 13:16:51 +01:00
Gian Maria Viglianti
892888796d Translated using Weblate (Italian)
Currently translated at 100.0% (140 of 140 strings)
2016-12-26 14:57:31 +01:00
Weblate
4f2826d2c2 Merge remote-tracking branch 'origin/master' 2016-12-26 10:23:57 +01:00
YFdyh000
7f824d725b Translated using Weblate (Chinese (Simplified))
Currently translated at 98.5% (138 of 140 strings)
2016-12-26 10:23:56 +01:00
naofum
da4096c4ef Translated using Weblate (Japanese)
Currently translated at 100.0% (140 of 140 strings)
2016-12-26 10:23:55 +01:00
Christian Schabesberger
1aed11c156 change ip address provider
removed null bomb
2016-12-25 19:32:38 +01:00
Christian Schabesberger
e99e944ac3 make share with newpipe part of newpipe 2016-12-25 19:28:40 +01:00
Christian Schabesberger
6e523d37ba add copyright notice to DownloadListener 2016-12-25 15:24:37 +01:00
Christian Schabesberger
2aebf6b522 Merge branch 'master' of git://github.com/fr3ts0n/NewPipe into fr3ts0n-master 2016-12-25 15:20:31 +01:00
Mladen Pejaković
3f740980a3 Translated using Weblate (Serbian)
Currently translated at 100.0% (140 of 140 strings)
2016-12-25 14:16:58 +01:00
Weblate
66b73d1592 Merge remote-tracking branch 'origin/master' 2016-12-25 12:44:13 +01:00
RACER
be4b03b84b Translated using Weblate (Japanese)
Currently translated at 100.0% (138 of 138 strings)
2016-12-25 12:44:13 +01:00
Osoitz
3594037efe Translated using Weblate (Basque)
Currently translated at 34.0% (47 of 138 strings)
2016-12-25 12:44:11 +01:00
Christian Schabesberger
38c5cb50fb fixed Downloader.getInstance() in unit tests 2016-12-24 17:11:29 +01:00
Christian Schabesberger
3767a96e0f moved on to version 0.8.6 2016-12-24 16:06:24 +01:00
Christian Schabesberger
937a387f4e rename reCaptchaException to ReCaptchaException 2016-12-24 15:19:40 +01:00
Christian Schabesberger
cd65f1dffc Merge branch 'reCaptcha' of git://github.com/be-neth/NewPipe into be-neth-reCaptcha 2016-12-24 14:13:12 +01:00
Christian Schabesberger
d4e6856cbe Merge pull request #394 from ngoisaosang/master
Try to fix accept SDK Licenses
2016-12-24 14:12:36 +01:00
ngoisaosang
f61d779108 Try to fix travis 2016-12-24 07:25:27 +07:00
ngoisaosang
b8b22d4d91 Fix travis 2016-12-23 13:47:20 +07:00
ngoisaosang
25d0e39736 Update gradle 2016-12-22 22:45:42 +07:00
ngoisaosang
79a9497e65 Fix travis build 2016-12-22 17:40:01 +07:00
Christian Schabesberger
c55dcccb1e Merge branch 'fix-channel-bannel-url' of git://github.com/coffeemakr/NewPipe into coffeemakr-fix-channel-bannel-url 2016-12-21 21:01:47 +01:00
Christian Schabesberger
820e606719 fix duration_background name 2016-12-21 21:00:05 +01:00
Christian Schabesberger
96291a8522 Merge branch 'coffeemakr-fix-yt-dublicated-result-page' 2016-12-21 20:56:40 +01:00
Christian Schabesberger
e7b52bd3b0 Merge pull request #392 from ksyko/patch-1
Fixes spelling
2016-12-21 20:42:03 +01:00
ksyko
dd3251c08d Fixes spelling 2016-12-21 20:38:51 +05:30
Coffeemakr
f4aabdd9b8 Accept SDK Licenses 2016-12-19 19:40:28 +01:00
Coffeemakr
cb1fe5f017 Try to fix travis 2016-12-19 19:36:24 +01:00
Coffeemakr
83837bde11 Google begins with page 1 so we add 1 to our page starting with 0 2016-12-19 19:28:16 +01:00
Coffeemakr
05189dadbf Fix banner extaction 2016-12-19 13:32:03 +01:00
Selim
dbb1f371b3 Translated using Weblate (Turkish)
Currently translated at 94.2% (130 of 138 strings)
2016-12-13 21:46:13 +01:00
Benoît Mauduit
5cc1bbc4bb Add missing Override decorator 2016-12-07 22:26:54 +01:00
Benoît Mauduit
53796043c3 Start reCaptchaActivity when reCaptcha is requested and fix Typo
* Fix typo setSearchWorkerResultListner to setSearchWorkerResultListener
2016-12-07 22:26:54 +01:00
Benoît Mauduit
a5ac528c02 Add reCaptchaException 2016-12-07 22:26:54 +01:00
Benoît Mauduit
54eb353d0d Add ReCaptcha Activity
* ReCaptchas are implemented using a simple WebView with Javascript enable.

 * All HTTP responses inside the WebView are catched (using onPageFinished())
 ** When Google reCatcha cookies are detected, register cookies to the
    Downloader class and Return to MainActivity
2016-12-07 22:26:54 +01:00
Benoît Mauduit
3391067cab Adding cookies member to Downloader 2016-12-07 22:26:54 +01:00
Benoît Mauduit
b4f595eb75 Make Downloader class a Singleton 2016-12-07 22:26:54 +01:00
Weblate
58bc0c17d0 Merge remote-tracking branch 'origin/master' 2016-12-02 10:24:55 +01:00
Cyxae Dexyc
4385404ad6 Translated using Weblate (French)
Currently translated at 98.5% (136 of 138 strings)
2016-12-02 10:24:54 +01:00
Marian Hanzel
61aadcffd2 Translated using Weblate (Slovak)
Currently translated at 100.0% (138 of 138 strings)
2016-12-02 10:24:52 +01:00
Christian Schabesberger
f575826394 fix unit tests 2016-11-20 19:01:06 +01:00
Christian Schabesberger
389959dd18 Merge pull request #366 from coffeemakr/delete-swiss-high-german
Delete Swiss High German translation
2016-11-20 15:43:37 +01:00
Christian Schabesberger
af4734eee3 update to sdk version 25 2016-11-18 23:56:08 +01:00
Christian Schabesberger
f76b37ec39 Merge branch 'master' of github.com:TeamNewPipe/NewPipe 2016-11-18 23:52:34 +01:00
Christian Schabesberger
379149fe2f update unit tests so it works with current updates 2016-11-18 23:52:17 +01:00
Christian Schabesberger
3bd477631c fixed spelling error 2016-11-18 22:08:53 +01:00
Freddy Morán Jr
72c0987bad Translated using Weblate (Spanish)
Currently translated at 100.0% (138 of 138 strings)
2016-11-10 03:46:02 +01:00
fr3ts0n
5bba8e02a6 add media scanner notification after successful download 2016-11-06 21:08:57 +01:00
Freddy Morán Jr
b270de3335 Translated using Weblate (Spanish)
Currently translated at 100.0% (138 of 138 strings)
2016-11-03 21:46:25 +01:00
Freddy Morán Jr
e22bcf0ac5 Translated using Weblate (Serbian)
Currently translated at 100.0% (138 of 138 strings)
2016-11-03 21:46:13 +01:00
Freddy Morán Jr
c1d55d828f Translated using Weblate (Portuguese)
Currently translated at 100.0% (138 of 138 strings)
2016-11-03 21:45:51 +01:00
Freddy Morán Jr
da77970328 Translated using Weblate (Indonesian)
Currently translated at 100.0% (138 of 138 strings)
2016-11-03 21:45:12 +01:00
Freddy Morán Jr
32f3caaee0 Translated using Weblate (German)
Currently translated at 100.0% (138 of 138 strings)
2016-11-03 21:44:57 +01:00
Дима Гайнуллин
8bbacb1d78 Translated using Weblate (Russian)
Currently translated at 88.4% (122 of 138 strings)
2016-11-03 18:45:52 +01:00
Nathan Follens
5904510410 Translated using Weblate (Dutch)
Currently translated at 100.0% (138 of 138 strings)
2016-10-30 00:44:27 +02:00
Enol P
e16624251b Translated using Weblate (Asturian)
Currently translated at 97.1% (134 of 138 strings)
2016-10-21 03:44:09 +02:00
zmni
389f22a0e5 Translated using Weblate (Indonesian)
Currently translated at 99.2% (137 of 138 strings)
2016-10-16 12:45:00 +02:00
zmni
7b91aa16b6 Translated using Weblate (Indonesian)
Currently translated at 95.6% (132 of 138 strings)
2016-10-13 21:45:17 +02:00
Jona Abdinghoff
89ec688632 Translated using Weblate (German)
Currently translated at 99.2% (137 of 138 strings)
2016-10-12 00:44:52 +02:00
Nathan Follens
fdd0d586c9 Translated using Weblate (Dutch)
Currently translated at 99.2% (137 of 138 strings)
2016-10-12 00:44:25 +02:00
Coffeemakr
6f5604791f Delete swiss high german 2016-10-11 07:30:18 +02:00
Gian Maria Viglianti
eb9fba4147 Translated using Weblate (Italian)
Currently translated at 100.0% (138 of 138 strings)
2016-10-10 18:45:06 +02:00
Weblate
afb62f729f Merge remote-tracking branch 'origin/master' 2016-10-04 15:45:09 +02:00
Nathan Follens
1ccc23dc9c Translated using Weblate (Dutch)
Currently translated at 68.8% (95 of 138 strings)
2016-10-04 15:45:07 +02:00
intrnl
7ea5cb9c5c Translated using Weblate (Indonesian)
Currently translated at 37.6% (52 of 138 strings)
2016-10-04 15:44:59 +02:00
Christian Schabesberger
c301d6e5d5 Merge branch 'master' of github.com:TeamNewPipe/NewPipe 2016-10-01 23:22:18 +02:00
naofum
44ad69b94d Translated using Weblate (Japanese)
Currently translated at 100.0% (138 of 138 strings)
2016-10-01 18:45:10 +02:00
Christian Schabesberger
d14515ab88 Merge remote-tracking branch 'origin/master' 2016-09-28 17:13:23 +02:00
Christian Schabesberger
01875b389d clean up extractor 2016-09-28 17:13:15 +02:00
Christian Schabesberger
5eef116aaa put Suggestion extraction into its own class 2016-09-28 12:53:23 +02:00
Weblate
442220debc Merge remote-tracking branch 'origin/master' 2016-09-28 12:45:55 +02:00
kamadi
4914caad51 Translated using Weblate (Russian)
Currently translated at 48.5% (67 of 138 strings)
2016-09-28 12:45:54 +02:00
Gian Maria Viglianti
08cab863f1 Translated using Weblate (Italian)
Currently translated at 98.5% (136 of 138 strings)
2016-09-28 12:45:54 +02:00
Marian Hanzel
02458d4fc1 Translated using Weblate (Slovak)
Currently translated at 98.5% (136 of 138 strings)
2016-09-28 12:45:51 +02:00
Christian Schabesberger
6ed4130b66 fix collisions 2016-09-28 11:54:35 +02:00
Felix Ableitner
5f7ee15d1e Launch video player in single task mode (fixes #154) 2016-09-28 13:09:42 +09:00
Christian Schabesberger
43afd5a2b8 clean up downloader thing 2016-09-27 22:59:04 +02:00
Christian Schabesberger
f9ac199c1f fixed .webm download locatiion issue 2016-09-27 21:33:26 +02:00
Christian Schabesberger
920c169d55 update CI batch in README 2016-09-27 20:22:01 +02:00
Christian Schabesberger
76ba2824a2 stability improvements 2016-09-27 20:18:41 +02:00
Christian Schabesberger
ca0d594547 cleaning away android stuff from extractor 2016-09-27 20:06:33 +02:00
Christian Schabesberger
44b6d900f0 Merge branch 'master' of github.com:TeamNewPipe/NewPipe 2016-09-27 14:58:54 +02:00
Christian Schabesberger
3b2c0186aa update issue teamplate 2016-09-27 14:58:46 +02:00
Christian Schabesberger
efa605700d update contributions link in the readme 2016-09-27 14:33:30 +02:00
Christian Schabesberger
cac360d37b add .github folder 2016-09-27 14:30:03 +02:00
Christian Schabesberger
75e28893fb update contribution guidelines once again 2016-09-27 14:14:59 +02:00
Christian Schabesberger
360a44b5a0 update contribution guidelines 2016-09-27 13:43:43 +02:00
Christian Schabesberger
2b89e24a4b make download dialog use radio button 2016-09-26 20:18:32 +02:00
Christian Schabesberger
931f34d2fd fixed related videos nullpointer exception 2016-09-26 18:01:39 +02:00
Christian Schabesberger
abfdcea4db moved on to 0.8.5 2016-09-26 17:32:03 +02:00
Christian Schabesberger
80b3b8ac0f change readme layout 2016-09-26 17:04:54 +02:00
Christian Schabesberger
60e18aa045 similar videos scroll bug workaround 2016-09-26 17:02:55 +02:00
Christian Schabesberger
85e2b124ab Merge branch 'master' of github.com:theScrabi/NewPipe 2016-09-25 21:22:37 +02:00
Christian Schabesberger
81a8cd0641 update to gradle2.2.0 2016-09-25 21:22:29 +02:00
Weblate
303805755d Merge remote-tracking branch 'origin/master' 2016-09-25 19:23:20 +02:00
Gian Maria Viglianti
38837d6424 Translated using Weblate (Italian)
Currently translated at 97.1% (134 of 138 strings)
2016-09-25 19:23:19 +02:00
Christian Schabesberger
8a582c2a24 fix weblate merge conflict 2016-09-25 19:23:10 +02:00
Tiago Roque Medeiros
5cfb65002d Translated using Weblate (Portuguese)
Currently translated at 99.2% (137 of 138 strings)
2016-09-22 18:45:35 +02:00
Benedikt Freisen
fa6dee45ec Translated using Weblate (German)
Currently translated at 98.5% (136 of 138 strings)
2016-09-20 16:56:29 +02:00
Sérgio Marques
af25fe93da Translated using Weblate (Portuguese)
Currently translated at 99.2% (137 of 138 strings)
2016-09-20 16:56:28 +02:00
naofum
395ad3e8ef Translated using Weblate (Japanese)
Currently translated at 99.2% (137 of 138 strings)
2016-09-18 09:45:36 +02:00
marxsouza12
2cbaca8968 Translated using Weblate (Portuguese)
Currently translated at 97.1% (134 of 138 strings)
2016-09-18 09:45:34 +02:00
Christian Schabesberger
bf90788e04 update featurs at readme
update featurs at readme once again
2016-09-15 10:35:22 +02:00
Christian Schabesberger
83ffb849cd update featurs at readme 2016-09-15 10:31:48 +02:00
Christian Schabesberger
a34a33e419 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-09-14 18:35:22 +02:00
Christian Schabesberger
57f620485f fix ui crash bug 2016-09-14 18:35:17 +02:00
Weblate
18cdde963b Merge remote-tracking branch 'origin/master' 2016-09-14 15:45:35 +02:00
Mladen Pejaković
6c1f472de3 Translated using Weblate (Serbian)
Currently translated at 99.2% (137 of 138 strings)
2016-09-14 15:45:35 +02:00
Christian Schabesberger
efd2ac353e fix WORLD_MODE_READABLE bug
blub
2016-09-14 11:29:40 +02:00
Christian Schabesberger
863bf9dc8b fix channel has no second page bug 2016-09-14 11:15:08 +02:00
Weblate
fd411c17cd Merge remote-tracking branch 'origin/master' 2016-09-14 00:50:31 +02:00
YFdyh000
5424c23d69 Translated using Weblate (Simplified Chinese)
Currently translated at 97.8% (135 of 138 strings)
2016-09-14 00:50:31 +02:00
Christian Schabesberger
b8a0801786 fixed bug regarding channels
acual fix
2016-09-14 00:50:18 +02:00
Christian Schabesberger
39ff1cd898 Merge pull request #357 from theScrabi/ref_crashreport
Refactore crashreport
2016-09-14 00:05:37 +02:00
Christian Schabesberger
a2a3b0575d gather all bug shit things 2016-09-13 23:39:32 +02:00
Christian Schabesberger
2b8954353d removed crash test line 2016-09-13 23:31:28 +02:00
Christian Schabesberger
9bd5aa0da4 add package field to crash report 2016-09-13 23:31:06 +02:00
Christian Schabesberger
af2cddee91 made acra catch and report errors 2016-09-13 23:24:49 +02:00
Christian Schabesberger
27bc414616 add copyright notice 2016-09-13 22:38:45 +02:00
Christian Schabesberger
14eaedd73a use intent system to pass errors to error activity 2016-09-13 22:36:47 +02:00
Christian Schabesberger
a2effef346 fix build tooles for CI 2016-09-13 00:21:02 +02:00
Christian Schabesberger
caf938f79f add channel extractor tests 2016-09-12 23:44:57 +02:00
Christian Schabesberger
8ececc11d2 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-09-12 23:07:31 +02:00
Christian Schabesberger
cf1d546683 add new play icon 2016-09-12 23:07:23 +02:00
Weblate
e8144f4906 Merge remote-tracking branch 'origin/master' 2016-09-12 22:35:28 +02:00
naofum
bfb6f14769 Translated using Weblate (Japanese)
Currently translated at 99.2% (136 of 137 strings)
2016-09-12 22:35:27 +02:00
Christian Schabesberger
ff1ba2b5bf Merge branch 'master' of github.com:theScrabi/NewPipe 2016-09-12 22:35:15 +02:00
Christian Schabesberger
8c26f29f94 shitty fix for detail progressbar 2016-09-12 17:49:49 +02:00
Weblate
bdd57f3b3e Merge remote-tracking branch 'origin/master' 2016-09-12 16:22:16 +02:00
YFdyh000
e09bf4d09c Translated using Weblate (Simplified Chinese)
Currently translated at 98.5% (135 of 137 strings)
2016-09-12 16:22:16 +02:00
Christian Schabesberger
e0dbf4c2cd fix settings updateSummary 2016-09-12 16:22:02 +02:00
Christian Schabesberger
4bba84af8a Merge pull request #316 from jaytj95/master
Added rewind capability to notification control
2016-09-12 00:57:53 +02:00
Christian Schabesberger
bd7077c1cf fix rising exception for empty related videos 2016-09-12 00:56:20 +02:00
Christian Schabesberger
a63128bd45 add addblock 2016-09-12 00:51:03 +02:00
Christian Schabesberger
6944f4a68a add copyright headers and update sdk 2016-09-12 00:33:11 +02:00
Christian Schabesberger
54ab0ab17e fix merge with add_cahnnels 2016-09-12 00:12:00 +02:00
Christian Schabesberger
2080bb2da1 Merge pull request #350 from KeizerDev/splash-screen
Added Splash Screen to bypass blank screen on start up.
2016-09-11 23:57:30 +02:00
Christian Schabesberger
cc74c98509 add bugrepport to channel acitivty 2016-09-11 23:15:22 +02:00
Christian Schabesberger
dd6c6ae03f seems to made it working 2016-09-10 18:47:35 +02:00
Christian Schabesberger
4f8ca9ef16 fucking brought it almost to work fuck 2016-09-10 18:28:48 +02:00
Christian Schabesberger
53059bcb91 level 1 of making loading more content work 2016-09-10 16:26:21 +02:00
Filip Sebastian
cb056f4f80 Translated using Weblate (Romanian)
Currently translated at 100.0% (133 of 133 strings)
2016-08-24 12:45:40 +02:00
Robert-Jan Keizer
05bfa8b85e Added splash screen to bypass blank screen on start up. 2016-08-22 01:13:09 +02:00
Christian Schabesberger
6dc5350c43 update gradle and fix load image error string 2016-08-20 00:56:10 +02:00
Enol P
5cdf807d92 Translated using Weblate (Asturian)
Currently translated at 100.0% (133 of 133 strings)
2016-08-18 06:44:10 +02:00
Enol P
9c2a9e64c2 Translated using Weblate (Asturian)
Currently translated at 100.0% (133 of 133 strings)
2016-08-16 03:43:01 +02:00
Enol P
3b60b801c2 Added translation using Weblate (Asturian) 2016-08-16 02:38:40 +02:00
Danial Behzadi
c78eb80686 Translated using Weblate (Persian)
Currently translated at 100.0% (133 of 133 strings)
2016-08-12 15:45:23 +02:00
Danial Behzadi
9b9da648c9 Translated using Weblate (Persian)
Currently translated at 100.0% (133 of 133 strings)
2016-08-10 15:33:17 +02:00
Danial Behzadi
adc2b9c43a Added translation using Weblate (Persian) 2016-08-10 14:21:05 +02:00
Weblate
b3954e9acd Merge remote-tracking branch 'origin/master' 2016-08-08 22:05:14 +02:00
Christian Schabesberger
6e36f0ef83 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-08-08 22:11:40 +02:00
Christian Schabesberger
64afb907e6 change icon 2016-08-08 22:11:32 +02:00
Rom1
3552125075 Translated using Weblate (French)
Currently translated at 100.0% (133 of 133 strings)
2016-08-08 22:05:13 +02:00
Christian Schabesberger
2601bf6d81 change view naming in detail fragment 2016-08-08 20:21:18 +02:00
David
3da032b7ee Update filepicker to the newest version and Fix for #343 2016-08-03 18:36:46 -03:00
Christian Schabesberger
7bea94144e fix search fragment progressbar 2016-08-03 17:18:05 +02:00
Dawid
40b08a593f Translated using Weblate (Polish)
Currently translated at 95.4% (127 of 133 strings)
2016-08-03 15:45:26 +02:00
Christian Schabesberger
5d06e8310d animate item button and made channel layout use recyclerview propper 2016-08-03 15:32:25 +02:00
Christian Schabesberger
1ab82dfa32 made channel activity use recycler view 2016-08-03 13:09:48 +02:00
Sérgio Marques
b93372926a Translated using Weblate (Portuguese)
Currently translated at 100.0% (133 of 133 strings)
2016-08-03 12:45:28 +02:00
Christian Schabesberger
557bcc40ef made detail fragment use recycler view 2016-08-03 00:54:03 +02:00
Christian Schabesberger
06e2e548be restructure detail activity 2016-08-03 00:12:58 +02:00
Christian Schabesberger
7a25588995 remove listactivity layout 2016-08-02 21:30:55 +02:00
Christian Schabesberger
8107337566 restructure ui 2016-08-02 21:17:54 +02:00
Christian Schabesberger
d6de11f54c remove video item list plemp 2016-08-02 20:59:53 +02:00
Christian Schabesberger
2f2334eac4 make search fagment handle video items 2016-08-02 18:38:05 +02:00
Christian Schabesberger
3a5b9203d8 put search fragment into own package 2016-08-02 15:06:02 +02:00
Christian Schabesberger
c46ce1170c add search fragment 2016-08-02 01:42:05 +02:00
Christian Schabesberger
1170c508b4 add new architecture 2016-08-02 01:26:12 +02:00
Christian Schabesberger
f34cacbc5c add recycler view adapter 2016-08-02 00:58:52 +02:00
Christian Schabesberger
4164195fae show channelvideos 2016-08-01 21:50:41 +02:00
Christian Schabesberger
c03b106118 add channel avatar 2016-08-01 11:48:52 +02:00
Dawid
c760a4e0ef Added translation using Weblate (Polish) 2016-08-01 09:28:48 +02:00
Christian Schabesberger
f3a73ecc4a add feed function 2016-08-01 02:10:38 +02:00
Christian Schabesberger
6beb36f92f get channel banner 2016-08-01 01:56:19 +02:00
Christian Schabesberger
033a4ecbe8 add now (actual) logo 2016-07-31 17:23:46 +02:00
Sérgio Marques
6360d61721 Translated using Weblate (Portuguese)
Currently translated at 100.0% (133 of 133 strings)
2016-07-31 16:20:39 +02:00
Christian Schabesberger
5dd3f6cd02 add new logo to assets 2016-07-31 14:40:19 +02:00
Utku BERBEROĞLU
cb3c595d2b Translated using Weblate (Turkish)
Currently translated at 34.5% (46 of 133 strings)
2016-07-30 18:46:18 +02:00
Marian Hanzel
f4414851be Translated using Weblate (Slovak)
Currently translated at 100.0% (133 of 133 strings)
2016-07-27 10:01:18 +02:00
Christian Schabesberger
9a0f61e60b add basics 2016-07-26 13:50:52 +02:00
naofum
22fc690c65 Translated using Weblate (Japanese)
Currently translated at 100.0% (133 of 133 strings)
2016-07-25 13:23:40 +02:00
Christian Schabesberger
c5583bd77b try to fix failing CI 2016-07-25 12:28:00 +02:00
Christian Schabesberger
8fbee92255 try to fix failing CI 2016-07-25 12:11:55 +02:00
Christian Schabesberger
1fd6685b3b removed orebot/tor support 2016-07-25 11:59:37 +02:00
Christian Schabesberger
e6fe1d2008 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-07-25 11:13:04 +02:00
Christian Schabesberger
c0ce14dba5 moved on to new sdk, and put settings activity result into its fragment 2016-07-25 11:12:54 +02:00
YFdyh000
9f315fb021 Translated using Weblate (Simplified Chinese)
Currently translated at 100.0% (133 of 133 strings)
2016-07-25 03:56:47 +02:00
Christian Schabesberger
dc46b3f6c0 Merge pull request #314 from satiricon/pref-filepicker
File picker for download preferences.
2016-07-25 00:48:48 +02:00
Christian Schabesberger
24dd94fba3 Merge pull request #317 from ggppjj/master
Change "click" to "tap".
2016-07-25 00:46:49 +02:00
Christian Schabesberger
d3d4e8c721 Merge pull request #321 from DevFactory/release/collection-interfaces-should-be-used-fix-1
Code quality fix - Declarations should use Java collection interfaces such as "List" rather than specific implementation.
2016-07-25 00:46:33 +02:00
Nigel
990d3fc714 Translated using Weblate (Chinese (Hong Kong))
Currently translated at 97.7% (130 of 133 strings)
2016-07-24 12:44:17 +02:00
Christian Schabesberger
9c82f0b12a moved to sdk version 24 2016-07-21 16:43:24 +02:00
Christian Schabesberger
47bdd2e565 Merge pull request #331 from Gracecr/patch-1
Allow for large times stamps fixing #330
2016-07-21 07:15:13 +02:00
David
9a5e82cb1e Updating code to make it compatible with master 2016-07-19 16:56:53 -03:00
David
2ab9db3c07 A little cleanup 2016-07-19 16:53:20 -03:00
David
b3fdd2b0cb Done with the file picker for the download settings 2016-07-19 16:53:20 -03:00
David
bd43efd2c2 The file picker is working and I'm reordering the code to make it easier to follow 2016-07-19 16:52:37 -03:00
David
36babcaf36 Trying to make last filepicker version work, maybe I'm having some memory problems 2016-07-19 16:51:14 -03:00
David
45be3fb0e8 Starting to add a filepicker to the directory preferences 2016-07-19 16:51:14 -03:00
Gracecr
c880047c4f Allows for large times stamps fixing #330
@scde submitted #330, along with a couple proposed fixes.
This is the second proposed fix, which allows for arbitrarily large
timestamps. All credit to @scde for this.
2016-07-14 16:50:57 -04:00
Christian Schabesberger
66e88829dd Merge pull request #327 from adelolmo/master
fix build. remove wrong xliff namespaces from spanish translation.
2016-07-04 17:46:52 +02:00
Andoni del Olmo
3add3d75a1 skip ads and channels from test. 2016-07-04 12:05:43 +02:00
Andoni del Olmo
8644a4542a skip ads and channels from test. 2016-07-04 11:43:18 +02:00
andoni
0b6bae6ce3 change test search term to avoid google ads. 2016-07-03 16:25:32 +02:00
Faisal Hameed
13346ab750 Fixing squid:S1319 - Declarations should use Java collection interfaces such as "List" rather than specific implementation. 2016-07-01 04:05:55 +05:00
andoni
f65c08431c support all variants of vnd.youtube url. 2016-06-30 20:21:54 +02:00
andoni
4cde97e65d fix build. remove wrong xliff namespaces from spanish translation. 2016-06-30 20:14:27 +02:00
Christian Schabesberger
049b36b1b6 Merge pull request #323 from DevFactory/release/public-static-fields-should-be-constants-fix-1
Code quality fix - "public static" fields should be constant.
2016-06-30 16:57:42 +02:00
Christian Schabesberger
faed0958b3 Merge pull request #322 from DevFactory/release/string-literals-should-not-be-duplicated-fix-1
Code quality fix - String literals should not be duplicated.
2016-06-30 16:56:41 +02:00
Christian Schabesberger
3b36b7f01b Merge pull request #324 from DevFactory/release/redundant-modifiers-should-not-be-used-fix-1
Code quality fix - Redundant modifiers should not be used.
2016-06-30 16:56:11 +02:00
Weblate
5a2b236e71 Merge remote-tracking branch 'origin/master' 2016-06-30 16:55:41 +02:00
Riccardo Boninsegna
e5db08b0a8 Translated using Weblate (Italian)
Currently translated at 100.0% (133 of 133 strings)
2016-06-30 16:55:41 +02:00
Coffeemaker
e29eeb5d3d Translated using Weblate (German)
Currently translated at 96.2% (128 of 133 strings)
2016-06-30 16:55:41 +02:00
Christian Schabesberger
6dac88c394 Merge pull request #325 from DevFactory/release/redundant-field-initializers-fix-1
Code quality fix - Redundant Field Initializer.
2016-06-30 16:55:35 +02:00
Riccardo Boninsegna
580a0069dc Translated using Weblate (Italian)
Currently translated at 100.0% (133 of 133 strings)
2016-06-29 22:28:04 +02:00
Coffeemaker
187d65ffa5 Added translation using Weblate (Swiss High German) 2016-06-29 18:54:53 +02:00
Christian Schabesberger
7b0ef1824f add warning to nod add newpipe to playstore 2016-06-28 22:37:24 +02:00
Faisal Hameed
404017cba3 Fixing squid:S1192 - String literals should not be duplicated. 2016-06-24 14:54:18 +05:00
Faisal Hameed
dd2398efad Fixing pmd:RedundantFieldInitializer - Redundant Field Initializer. 2016-06-24 05:44:42 +05:00
Faisal Hameed
a44518a757 Fixing squid:S2333 - Redundant modifiers should not be used. 2016-06-24 05:44:09 +05:00
Faisal Hameed
83eb83025a Fixing squid:S1444 - "public static" fields should be constant. 2016-06-24 05:30:46 +05:00
Gabriel Jones
464a113f11 Change "click" to "tap". 2016-06-23 11:41:01 -04:00
Weblate
25a776cc93 Merge remote-tracking branch 'origin/master' 2016-06-22 23:41:13 +02:00
Rom1
7d19fb878d Translated using Weblate (French)
Currently translated at 100.0% (133 of 133 strings)
2016-06-22 23:41:12 +02:00
Christian Schabesberger
f5aef6879a Update CONTRIBUTING.md
fixed broken slack link
2016-06-22 23:41:09 +02:00
hatsunearu
29014d7b4a Translated using Weblate (Korean)
Currently translated at 85.7% (114 of 133 strings)
2016-06-22 09:45:15 +02:00
hd hd
9668a78732 Translated using Weblate (Hungarian)
Currently translated at 100.0% (133 of 133 strings)
2016-06-22 03:44:49 +02:00
devnoname120
a1aafb17c9 Translated using Weblate (French)
Currently translated at 100.0% (133 of 133 strings)

Not literally translated because used here: ddc3b47dfa/app/src/main/java/org/schabi/newpipe/VideoItemListFragment.java (L182)
2016-06-22 00:44:36 +02:00
Murat Dikici
9883678fd9 Translated using Weblate (Turkish)
Currently translated at 17.2% (23 of 133 strings)
2016-06-20 09:45:49 +02:00
hd hd
ba72379aa9 Translated using Weblate (Hungarian)
Currently translated at 100.0% (133 of 133 strings)
2016-06-20 00:58:09 +02:00
devnoname120
3206fef865 Translated using Weblate (French)
Currently translated at 81.2% (108 of 133 strings)
2016-06-19 22:55:25 +02:00
Freddy Morán Jr
06b6216b9d Translated using Weblate (Spanish)
Currently translated at 100.0% (133 of 133 strings)
2016-06-18 21:45:48 +02:00
Marian Hanzel
5458606abe Translated using Weblate (Slovak)
Currently translated at 100.0% (133 of 133 strings)
2016-06-18 12:35:17 +02:00
Murat Dikici
ad5cf99d9e Added translation using Weblate (Turkish) 2016-06-18 08:40:56 +02:00
Freddy Morán Jr
0445086e67 Translated using Weblate (Spanish)
Currently translated at 100.0% (133 of 133 strings)
2016-06-16 15:11:35 +02:00
Jason John
51641dcc9a Added rewind capability to notification control ( seekTo(0) ) 2016-06-16 09:11:18 -04:00
David
d1e698185e A little cleanup 2016-06-16 07:58:09 -03:00
David
d145a3e967 Done with the file picker for the download settings 2016-06-15 12:56:03 -03:00
David
4a5190292c The file picker is working and I'm reordering the code to make it easier to follow 2016-06-15 12:56:03 -03:00
David
1b7cece306 Trying to make last filepicker version work, maybe I'm having some memory problems 2016-06-15 12:55:37 -03:00
David
181c83090d Starting to add a filepicker to the directory preferences 2016-06-15 12:53:02 -03:00
Christian Schabesberger
54c32b9fe2 moved on to version 0.8.0:
* moved on to version 0.8.0
* removed posibility to use *.jar files
* updated dependend libraries
2016-06-12 18:24:16 +02:00
David
9d5951765f Fix for #310 2016-06-08 12:35:54 -03:00
David
ddc3b47dfa Fix for #308 part 2 2016-06-07 11:43:13 -03:00
David
59523d6a08 Fix for #308 2016-06-07 11:32:31 -03:00
Christian Schabesberger
686f395158 Merge pull request #307 from mingchen/master
Upgrade gradle wrapper to 2.10 and fix compile errors.
2016-06-04 10:54:12 +02:00
Ming Chen
f7b7340b30 Fix compile error due to improper define of xmlns 2016-06-03 16:13:30 -07:00
Ming Chen
9bcdad0218 Upgrade wrapper to 2.10 2016-06-03 15:53:02 -07:00
Matej U
ff4601f487 Translated using Weblate (Slovenian)
Currently translated at 100.0% (133 of 133 strings)
2016-06-03 10:49:16 +02:00
Renan Souza do Nascimento
535cebde51 Translated using Weblate (Portuguese)
Currently translated at 99.2% (132 of 133 strings)
2016-05-31 00:45:17 +02:00
Weblate
ed23faa455 Merge remote-tracking branch 'origin/master' 2016-05-27 15:29:12 +02:00
naofum
0c695d721d Translated using Weblate (Japanese)
Currently translated at 100.0% (133 of 133 strings)
2016-05-27 15:29:12 +02:00
Benedikt Freisen
d7a208dcee Translated using Weblate (German)
Currently translated at 91.7% (122 of 133 strings)
2016-05-27 15:29:11 +02:00
Christian Schabesberger
3eb2a26e4e blub commit 2016-05-27 15:29:02 +02:00
Mladen Pejaković
cc2d365e5a Translated using Weblate (Serbian)
Currently translated at 100.0% (133 of 133 strings)
2016-05-26 22:41:03 +02:00
naofum
76ac2cc58e Translated using Weblate (Japanese)
Currently translated at 100.0% (133 of 133 strings)
2016-05-26 12:44:04 +02:00
Christian Schabesberger
aee26fcffc add downloads menu item to detail fragment 2016-05-26 00:11:42 +02:00
Christian Schabesberger
685eebeb56 add title to activitys 2016-05-25 23:51:22 +02:00
Christian Schabesberger
f23ae091cc add icons for progress tiles 2016-05-25 23:35:27 +02:00
Christian Schabesberger
1421dca35f clean up gigaget code 2016-05-25 23:08:15 +02:00
Christian Schabesberger
39c2f31a22 changed color of download blocks 2016-05-25 22:59:32 +02:00
Christian Schabesberger
239ef1c238 add action for downloads menu item 2016-05-25 22:34:36 +02:00
Christian Schabesberger
466ba93750 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-05-25 22:19:47 +02:00
Marian Hanzel
72007a0162 Translated using Weblate (Slovak)
Currently translated at 100.0% (129 of 129 strings)
2016-05-25 19:50:47 +02:00
David
26c0445b83 Fix for #273 2016-05-25 08:27:15 -03:00
Christian Schabesberger
6f6c1704d4 add downloads menu item 2016-05-24 14:06:49 +02:00
Weblate
14aa6de422 Merge remote-tracking branch 'origin/master' 2016-05-24 13:51:33 +02:00
Mladen Pejaković
eeb770ffe3 Translated using Weblate (Serbian)
Currently translated at 100.0% (129 of 129 strings)
2016-05-24 13:51:33 +02:00
David
382ac3470b Fix for #298 2016-05-24 08:51:08 -03:00
naofum
3abfb08090 Translated using Weblate (Japanese)
Currently translated at 100.0% (129 of 129 strings)
2016-05-23 13:24:57 +02:00
Matej U
b4aac839c9 Translated using Weblate (Slovenian)
Currently translated at 100.0% (129 of 129 strings)
2016-05-22 22:29:22 +02:00
YFdyh000
da984c23df Translated using Weblate (Simplified Chinese)
Currently translated at 100.0% (129 of 129 strings)
2016-05-22 16:14:29 +02:00
Mladen Pejaković
cab770159d Translated using Weblate (Serbian)
Currently translated at 100.0% (129 of 129 strings)
2016-05-22 13:56:29 +02:00
Christian Schabesberger
7c2ff977d8 Merge branch 'download-manager' of git://github.com/satiricon/NewPipe into satiricon-download-manager 2016-05-22 12:47:24 +02:00
Christian Schabesberger
5bd9334f8f Merge branch 'master' of github.com:theScrabi/NewPipe 2016-05-22 12:44:41 +02:00
Christian Schabesberger
c5544df64c made StreamExtractor use StreamPreviewInfoCollector 2016-05-22 12:39:57 +02:00
Christian Schabesberger
c85e3c07d6 Merge pull request #287 from prashantkhurana/fix/Media-controls-on-main-screen
Added media volume control on main screen Fixes #38
2016-05-22 09:18:23 +02:00
Christian Schabesberger
674e1c0519 Merge pull request #294 from prashantkhurana/Feature/Hide-uploader-bug
Fix to hide uploader correctly
2016-05-22 09:16:37 +02:00
Prashant Khurana
7154a1edb8 Fix to hide uploader correctly 2016-05-15 22:20:28 -04:00
Licaon Kter
be1252e0e6 Translated using Weblate (Romanian)
Currently translated at 64.8% (70 of 108 strings)
2016-05-12 15:45:25 +02:00
Christian Schabesberger
a4ce6c707c update support lib 2016-05-10 00:26:32 +02:00
David
affce74b84 Added menu to download activity 2016-05-02 10:47:18 -03:00
David
730de4061f deleted some unused code and assets 2016-05-02 10:47:18 -03:00
David
3beafa2a74 Added new download dialog 2016-05-02 10:47:18 -03:00
David
c622923edd Fixed the download dialog. Next take it to the previous activity 2016-05-02 10:47:18 -03:00
David
6940021293 Fixed dir settings 2016-05-02 10:47:18 -03:00
David
0156a4f39e Added back button to download activity ActionBar 2016-05-02 10:47:18 -03:00
David
4bae12aa55 Embedded GigaGet download manager. First try. 2016-05-02 10:47:18 -03:00
M2ck
f08b1224c9 Translated using Weblate (French)
Currently translated at 100.0% (108 of 108 strings)
2016-05-02 15:44:32 +02:00
Prashant Khurana
477355db8f Added media volume control on main screen Fixes #38 2016-05-01 21:49:14 -04:00
Allan Nordhøy
11c89165c5 Translated using Weblate (Norwegian Bokmål)
Currently translated at 92.5% (100 of 108 strings)
2016-05-01 00:44:56 +02:00
riotism
825f28ab9a Translated using Weblate (Chinese (Hong Kong))
Currently translated at 92.5% (100 of 108 strings)
2016-04-28 00:44:12 +02:00
Marian Hanzel
54ff5e1dc6 Translated using Weblate (Slovak)
Currently translated at 100.0% (108 of 108 strings)
2016-04-27 18:45:19 +02:00
Gian Maria Viglianti
9b46418628 Translated using Weblate (Italian)
Currently translated at 100.0% (108 of 108 strings)
2016-04-25 13:12:42 +02:00
Benedikt Freisen
04597a9faf Translated using Weblate (German)
Currently translated at 100.0% (108 of 108 strings)
2016-04-18 21:24:55 +02:00
naofum
5b0994dc85 Translated using Weblate (Japanese)
Currently translated at 100.0% (108 of 108 strings)
2016-04-18 15:02:56 +02:00
Christian Schabesberger
7c852c69a3 add queeing videos as an future feature 2016-04-17 15:49:35 +02:00
devnoname120
df47e94ceb Translated using Weblate (French)
Currently translated at 100.0% (108 of 108 strings)
2016-04-17 03:44:30 +02:00
Sérgio Marques
3b68004005 Translated using Weblate (Portuguese)
Currently translated at 100.0% (108 of 108 strings)
2016-04-16 18:39:29 +02:00
devnoname120
5a9c327938 Translated using Weblate (French)
Currently translated at 99.0% (108 of 108 strings)
2016-04-15 01:10:28 +02:00
M2ck
3e31e9783c Translated using Weblate (French)
Currently translated at 99.0% (107 of 108 strings)
2016-04-15 01:10:25 +02:00
Yoo
46fb3639ec Translated using Weblate (Hungarian)
Currently translated at 99.0% (107 of 108 strings)
2016-04-14 18:44:40 +02:00
Rom1
a6eba57099 Translated using Weblate (French)
Currently translated at 99.0% (107 of 108 strings)
2016-04-13 14:49:46 +02:00
M2ck
c8481f961a Translated using Weblate (French)
Currently translated at 98.1% (106 of 108 strings)
2016-04-13 14:49:07 +02:00
Robin van der Vliet
56329f43fb Translated using Weblate (Esperanto)
Currently translated at 71.2% (77 of 108 strings)
2016-04-11 18:44:19 +02:00
Matej U
793fbfb5be Translated using Weblate (Slovenian)
Currently translated at 100.0% (108 of 108 strings)
2016-04-09 20:51:20 +02:00
Rom1
1d8334b762 Translated using Weblate (French)
Currently translated at 93.5% (101 of 108 strings)
2016-04-09 18:44:35 +02:00
Rom1
19330ac415 Translated using Weblate (English)
Currently translated at 100.0% (108 of 108 strings)
2016-04-09 18:44:21 +02:00
Ibrahim Derraz
7a015a0bda Translated using Weblate (French)
Currently translated at 91.6% (99 of 108 strings)
2016-04-07 16:49:27 +02:00
Rom1
f29c422c61 Translated using Weblate (French)
Currently translated at 90.7% (98 of 108 strings)
2016-04-07 16:49:10 +02:00
Ibrahim Derraz
99a369f604 Translated using Weblate (French)
Currently translated at 90.7% (98 of 108 strings)
2016-04-07 16:47:48 +02:00
Rom1
c1f0fb36ac Translated using Weblate (French)
Currently translated at 89.8% (97 of 108 strings)
2016-04-07 16:47:32 +02:00
Ibrahim Derraz
fa0a8905f7 Translated using Weblate (French)
Currently translated at 89.8% (97 of 108 strings)
2016-04-07 16:47:21 +02:00
Rom1
4e63a3269e Translated using Weblate (French)
Currently translated at 88.8% (96 of 108 strings)
2016-04-07 16:46:47 +02:00
Ibrahim Derraz
0f1873e295 Translated using Weblate (French)
Currently translated at 87.9% (95 of 108 strings)
2016-04-07 16:40:26 +02:00
Rom1
23fd28afd5 Translated using Weblate (French)
Currently translated at 86.1% (93 of 108 strings)
2016-04-07 16:38:33 +02:00
naofum
ad5a813a9a Translated using Weblate (Japanese)
Currently translated at 100.0% (108 of 108 strings)
2016-04-07 15:38:19 +02:00
Ibrahim Derraz
f245eedbdf Translated using Weblate (French)
Currently translated at 82.4% (89 of 108 strings)
2016-04-07 15:18:55 +02:00
Rom1
1ce6a6e8c5 Translated using Weblate (French)
Currently translated at 80.5% (87 of 108 strings)
2016-04-07 15:18:38 +02:00
Ibrahim Derraz
0ea7b5526c Translated using Weblate (French)
Currently translated at 80.5% (87 of 108 strings)
2016-04-07 15:18:07 +02:00
Rom1
b41e88f8f3 Translated using Weblate (French)
Currently translated at 79.6% (86 of 108 strings)
2016-04-07 15:17:56 +02:00
Ibrahim Derraz
82b9e79d99 Translated using Weblate (French)
Currently translated at 79.6% (86 of 108 strings)
2016-04-07 15:17:35 +02:00
Rom1
a5383fadb1 Translated using Weblate (French)
Currently translated at 74.0% (80 of 108 strings)
2016-04-07 15:15:24 +02:00
Ibrahim Derraz
bd7fb9bbe4 Translated using Weblate (French)
Currently translated at 73.1% (79 of 108 strings)
2016-04-07 15:15:14 +02:00
Rom1
1ddd0a333c Translated using Weblate (French)
Currently translated at 72.2% (78 of 108 strings)
2016-04-07 15:14:40 +02:00
Ibrahim Derraz
084fec08a6 Translated using Weblate (French)
Currently translated at 72.2% (78 of 108 strings)
2016-04-07 15:14:23 +02:00
Rom1
2b51448b49 Translated using Weblate (French)
Currently translated at 71.2% (77 of 108 strings)
2016-04-07 15:13:14 +02:00
Ibrahim Derraz
f4eee83477 Translated using Weblate (French)
Currently translated at 71.2% (77 of 108 strings)
2016-04-07 15:12:02 +02:00
Rom1
cd622c9e06 Translated using Weblate (French)
Currently translated at 70.3% (76 of 108 strings)
2016-04-07 15:11:52 +02:00
Ibrahim Derraz
7077ebfde2 Translated using Weblate (French)
Currently translated at 70.3% (76 of 108 strings)
2016-04-07 15:11:41 +02:00
Rom1
4862fecb12 Translated using Weblate (French)
Currently translated at 69.4% (75 of 108 strings)
2016-04-07 15:10:58 +02:00
YFdyh000
c189933705 Translated using Weblate (Simplified Chinese)
Currently translated at 100.0% (108 of 108 strings)
2016-04-06 23:14:48 +02:00
Weblate
9c3f7a9139 Merge remote-tracking branch 'origin/master' 2016-04-06 23:12:51 +02:00
Zhaofeng Li
382bf5e936 Translated using Weblate (Simplified Chinese)
Currently translated at 100.0% (108 of 108 strings)
2016-04-06 23:12:51 +02:00
Christian Schabesberger
e2fac962f3 Merge pull request #261 from zhaofengli/ui-strings-ocd-cure
Let's tweak the UI strings a bit
2016-04-06 23:12:47 +02:00
Gian Maria Viglianti
3071ebc0d5 Translated using Weblate (Italian)
Currently translated at 100.0% (108 of 108 strings)
2016-04-06 19:16:15 +02:00
Zhaofeng Li
a5fc6db1fa default_resolution_title: Fix capitalization
"Default Resolution" -> "Default resolution"

See https://www.google.com/design/spec/style/writing.html#writing-capitalization-punctuation
2016-04-06 20:08:29 +08:00
Zhaofeng Li
8060c6a775 strings.xml: Fix grammar
"Download path video" -> "Video download path"
"Download path audio" -> "Audio download path"
2016-04-06 20:06:00 +08:00
Zhaofeng Li
2a6e7f300c search_language_title: Change "Preferable" to "Preferred"
Why? See http://english.stackexchange.com/questions/128996/how-would-one-know-when-to-choose-preferred-or-preferable
2016-04-06 20:02:40 +08:00
Zhaofeng Li
98afe79eaa strings.xml: Remove unnecessary punctuations
Periods, colons and other unnecessary punctuations should not be used in labels.
See https://www.google.com/design/spec/style/writing.html#writing-capitalization-punctuation
2016-04-06 20:02:22 +08:00
halcyonest
a35590f9ea Translated using Weblate (English)
Currently translated at 100.0% (108 of 108 strings)
2016-03-29 03:44:20 +02:00
Marian Hanzel
f14f8c35b8 Translated using Weblate (Slovak)
Currently translated at 100.0% (108 of 108 strings)
2016-03-28 18:06:19 +02:00
Matej U
aa5c510c99 Translated using Weblate (Slovenian)
Currently translated at 100.0% (108 of 108 strings)
2016-03-27 18:57:00 +02:00
Benedikt Freisen
59f33a8def Translated using Weblate (German)
Currently translated at 100.0% (108 of 108 strings)
2016-03-27 16:19:49 +02:00
naofum
dbb4df598c Translated using Weblate (Japanese)
Currently translated at 100.0% (108 of 108 strings)
2016-03-27 03:45:53 +02:00
halcyonest
8452f52da0 Translated using Weblate (Korean)
Currently translated at 100.0% (108 of 108 strings)
2016-03-27 03:40:44 +02:00
Christian Schabesberger
db6613f562 yet another try to fix that test -.- 2016-03-25 20:19:43 +01:00
Christian Schabesberger
44d2775437 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-03-25 20:03:05 +01:00
Christian Schabesberger
a3326dc598 another try to fixe shitty viewcount test 2016-03-25 20:02:50 +01:00
Christian Schabesberger
0cd56ddeb8 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-03-25 19:37:59 +01:00
Christian Schabesberger
2a7f729e73 fixed unit test 2016-03-25 19:37:48 +01:00
Weblate
18301d8f8b Merge remote-tracking branch 'origin/master' 2016-03-25 19:34:47 +01:00
YFdyh000
8286437055 Translated using Weblate (Simplified Chinese)
Currently translated at 100.0% (108 of 108 strings)
2016-03-25 19:34:46 +01:00
Christian Schabesberger
1bef7fbbf3 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-03-25 19:08:12 +01:00
YFdyh000
21e8318643 Translated using Weblate (Simplified Chinese)
Currently translated at 100.0% (108 of 108 strings)
2016-03-25 19:06:56 +01:00
Christian Schabesberger
381f054daf Merge branch 'Start-screen-hint' of git://github.com/Ashanmaril/NewPipe into Ashanmaril-Start-screen-hint 2016-03-25 19:05:56 +01:00
Christian Schabesberger
c05d9303a9 fixed download location 2016-03-25 19:01:22 +01:00
Weblate
cca72a9e4e Merge remote-tracking branch 'origin/master' 2016-03-25 18:58:08 +01:00
Oleksandr Los
d4463e5f30 Translated using Weblate (Ukrainian)
Currently translated at 71.0% (76 of 107 strings)
2016-03-25 18:58:08 +01:00
Ibrahim Derraz
92155e2154 Translated using Weblate (French)
Currently translated at 65.4% (70 of 107 strings)
2016-03-25 18:58:07 +01:00
Christian Schabesberger
287fd0bf1e Merge branch 'master' of github.com:theScrabi/NewPipe 2016-03-25 13:57:19 +01:00
Christian Schabesberger
9e910d5501 fixed commons-lang problem & moved on to 0.7.8 2016-03-25 13:56:24 +01:00
YFdyh000
ff54b4d0c9 Translated using Weblate (Simplified Chinese)
Currently translated at 100.0% (107 of 107 strings)
2016-03-25 06:45:09 +01:00
Oleksandr Los
af0b841bc3 Translated using Weblate (Ukrainian)
Currently translated at 100% (0 of 0 strings)

Created new translation.
2016-03-24 22:57:17 +01:00
Matej U
665ea85613 Translated using Weblate (Slovenian)
Currently translated at 100.0% (107 of 107 strings)
2016-03-24 21:45:10 +01:00
Benedikt Freisen
de635392c6 Translated using Weblate (German)
Currently translated at 100.0% (107 of 107 strings)
2016-03-23 12:44:33 +01:00
YFdyh000
7814cca3d5 Translated using Weblate (Simplified Chinese)
Currently translated at 100.0% (107 of 107 strings)
2016-03-23 06:12:36 +01:00
Hayden
6c7204eae0 Show/hide message 2016-03-22 20:05:43 -06:00
Hayden
834d647011 Merge remote-tracking branch 'github/Start-screen-hint' into Start-screen-hint
# Conflicts:
#	app/src/main/java/org/schabi/newpipe/VideoItemListActivity.java
2016-03-22 19:59:26 -06:00
Hayden
d872263b55 Got rid of imageview from testing 2016-03-22 19:55:00 -06:00
Hayden
4f8e4ca0ad Got rid of useless Toast from testing 2016-03-22 19:53:55 -06:00
Hayden
2abc9d0210 Text hint to start a search 2016-03-22 19:39:31 -06:00
Matej U
36fb942ce6 Translated using Weblate (Slovenian)
Currently translated at 100.0% (107 of 107 strings)
2016-03-22 19:10:20 +01:00
Tomáš Martykán
56476b35e3 Translated using Weblate (Czech)
Currently translated at 66.3% (71 of 107 strings)
2016-03-21 18:44:27 +01:00
hydroid7
38b3835891 Translated using Weblate (Hungarian)
Currently translated at 58.8% (63 of 107 strings)
2016-03-20 12:44:38 +01:00
naofum
ccf5be116a Translated using Weblate (Japanese)
Currently translated at 100.0% (107 of 107 strings)
2016-03-14 13:04:00 +01:00
Weblate
794ae4c5da Merge remote-tracking branch 'origin/master' 2016-03-13 22:38:50 +01:00
Mladen Pejaković
060e744924 Translated using Weblate (Serbian)
Currently translated at 98.1% (105 of 107 strings)
2016-03-13 22:38:50 +01:00
Christian Schabesberger
de62ed772f Merge branch 'master' of https://github.com/kamadi/NewPipe into kamadi-master 2016-03-13 22:36:33 +01:00
Christian Schabesberger
6a8c4a65c5 Merge pull request #237 from DevFactory/release/general-code-quality-fix-2
General code quality fix-2
2016-03-13 22:30:24 +01:00
Christian Schabesberger
03738aeb27 merged my changes with them of rrooij 2016-03-13 22:22:18 +01:00
Weblate
243cb8569e Merge remote-tracking branch 'origin/master' 2016-03-13 02:59:46 +01:00
Mladen Pejaković
1bd660fbbe Translated using Weblate (Serbian)
Currently translated at 98.1% (104 of 106 strings)
2016-03-13 02:59:46 +01:00
Christian Schabesberger
fec80b39f0 Merge pull request #238 from rrooij/yt_streampreviewextractor
Move YoutubeStreamPreviewInfoExtractor to separate class
2016-03-13 02:59:43 +01:00
rrooij
21768432c8 Move YoutubeStreamPreviewInfoExtractor to separate class
The class should be separate because channel support in the future would require video preview extraction too, which doesn't differ much from the extraction done from the search results.
2016-03-12 18:15:20 +01:00
Benedikt Freisen
e9b900ff28 Translated using Weblate (German)
Currently translated at 100.0% (106 of 106 strings)
2016-03-12 11:59:04 +01:00
naofum
c57cb8fec1 Translated using Weblate (Japanese)
Currently translated at 100.0% (106 of 106 strings)
2016-03-12 06:28:19 +01:00
Matej U
247681e3ef Translated using Weblate (Slovenian)
Currently translated at 100.0% (106 of 106 strings)
2016-03-11 23:46:28 +01:00
Faisal Hameed
2f9142419a Fixing squid:S1155, squid:S2293, squid:S1488 2016-03-12 02:01:47 +05:00
Christian Schabesberger
b84eb3df7f made stream type part of abstractVideoinfo 2016-03-11 16:20:02 +01:00
Christian Schabesberger
4058ec2ee9 fixed another livestream related issue 2016-03-11 15:43:50 +01:00
Christian Schabesberger
23a9061871 changed autoplay text 2016-03-11 15:10:13 +01:00
Weblate
9e95ca10b2 Merge remote-tracking branch 'origin/master' 2016-03-11 15:07:20 +01:00
Christian Schabesberger
4c0809d3d3 Translated using Weblate (German)
Currently translated at 100.0% (104 of 104 strings)
2016-03-11 15:07:20 +01:00
Christian Schabesberger
d43365f6e6 add custom error report function 2016-03-11 14:56:41 +01:00
Christian Schabesberger
c6ccc2b20d Merge pull request #232 from DevFactory/release/null-pointer-should-not-be-dereferenced-fix-1
Code quality fix - Null pointers should not be dereferenced.
2016-03-11 14:15:41 +01:00
Christian Schabesberger
31dd68be1d Merge pull request #233 from DevFactory/release/useless-parentheses-should-be-removed-fix-1
Code quality fix - Useless parentheses around expressions should be removed to prevent any misunderstanding.
2016-03-11 14:14:29 +01:00
Christian Schabesberger
1c94620c06 Merge pull request #234 from DevFactory/release/variable-should-comply-with-naming-conventions-fix-1
Code quality fix - Local variable and method parameter names should comply with a naming convention.
2016-03-11 14:13:51 +01:00
Weblate
82d214faa6 Merge remote-tracking branch 'origin/master' 2016-03-11 14:12:50 +01:00
Sérgio Marques
04b2e3689c Translated using Weblate (Portuguese)
Currently translated at 100.0% (104 of 104 strings)
2016-03-11 14:12:50 +01:00
Benedikt Volkmer
f00b8a3941 Translated using Weblate (German)
Currently translated at 100.0% (104 of 104 strings)
2016-03-11 14:12:49 +01:00
Henk de Vries
390cc9cfc9 Translated using Weblate (Dutch)
Currently translated at 95.1% (99 of 104 strings)
2016-03-11 14:12:49 +01:00
Christian Schabesberger
8259872e2d Merge pull request #235 from DevFactory/release/utility-classes-should-not-have-public-constructors-fix-1
Code quality fix - Utility classes should not have public constructors.
2016-03-11 14:12:45 +01:00
Faisal Hameed
1a3aaf86ee Fixing squid:S2259- Null pointers should not be dereferenced. 2016-03-10 15:07:23 +05:00
Faisal Hameed
cade4f932d Fixing squid:S00117- Local variable and method parameter names should comply with a naming convention. 2016-03-10 15:01:38 +05:00
Faisal Hameed
eb060602cd Fixing squid:S1118 - Utility classes should not have public constructors. 2016-03-10 14:50:42 +05:00
Faisal Hameed
805f046696 Fixing squid:UselessParenthesesCheck - Useless parentheses around expressions should be removed to prevent any misunderstanding. 2016-03-10 14:41:12 +05:00
Matej U
35e11e43de Translated using Weblate (Slovenian)
Currently translated at 100.0% (104 of 104 strings)
2016-03-08 21:22:44 +01:00
Mohamad Hasan Al Banna
ba15c6dc60 Translated using Weblate (Indonesian)
Currently translated at 100% (0 of 0 strings)

Created new translation.
2016-03-08 16:29:26 +01:00
Christian Schabesberger
569c227a99 try to give gradle more memory for CI build 2016-03-08 02:43:00 +01:00
Christian Schabesberger
8fd7599158 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-03-08 02:22:35 +01:00
Christian Schabesberger
19418e5dfb fixed another parsing but related to livestreams 2016-03-08 02:22:23 +01:00
Christian Schabesberger
f90a163ede add --info to buildscript 2016-03-08 01:25:07 +01:00
Christian Schabesberger
8fb1fd3602 fixed image loading bug 2016-03-08 01:24:45 +01:00
Christian Schabesberger
0dbf2a347f moved on to version 0.7.7 2016-03-08 01:10:33 +01:00
Christian Schabesberger
38742fd5e8 fixed values-iw build failure 2016-03-08 01:09:39 +01:00
Weblate
67ce7e0979 Merge remote-tracking branch 'origin/master' 2016-03-08 01:06:49 +01:00
Benedikt Freisen
21a7e52f9a Translated using Weblate (German)
Currently translated at 99.0% (103 of 104 strings)
2016-03-08 01:06:49 +01:00
Christian Schabesberger
fcb445a381 removed --stacktrace form CI buildscript 2016-03-08 01:02:01 +01:00
Christian Schabesberger
f6450d4b4d removed not or almost not existing translations 2016-03-07 19:15:01 +01:00
Christian Schabesberger
a01d1b89b6 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-03-07 18:51:51 +01:00
Christian Schabesberger
0c9b6582cc made CI script print stack trace 2016-03-07 18:51:43 +01:00
Christian Schabesberger
2d47daabf8 add xxxhdpi app icon 2016-03-07 15:03:26 +01:00
Weblate
ce20cbe435 Merge remote-tracking branch 'origin/master' 2016-03-07 15:00:43 +01:00
Matej U
99e5415bfc Translated using Weblate (Slovenian)
Currently translated at 87.5% (91 of 104 strings)
2016-03-07 15:00:42 +01:00
madiyar
b2d935dd6d Restoring search query after orientation change in two pane mode 2016-03-07 13:05:05 +06:00
madiyar
eb66cc5db8 Restoring search query after orientation change 2016-03-07 12:58:48 +06:00
naofum
6d6b8363a8 Translated using Weblate (Japanese)
Currently translated at 100.0% (104 of 104 strings)
2016-03-06 12:19:11 +01:00
Mladen Pejaković
bf79b02e15 Translated using Weblate (Serbian)
Currently translated at 100.0% (104 of 104 strings)
2016-03-05 18:57:47 +01:00
Christian Schabesberger
3ce7eda3eb made newpipe handle not available like/dislike count 2016-03-05 18:35:28 +01:00
Christian Schabesberger
378e6b6547 fixed fix portrait view 2016-03-05 17:49:11 +01:00
Christian Schabesberger
f63b35e2c0 fixed search error 2016-03-05 17:35:57 +01:00
Christian Schabesberger
9a480cbe3e fixed backarrow on player_activity 2016-03-05 17:16:28 +01:00
Christian Schabesberger
76ca937bb8 set tor into experimental state 2016-03-05 17:04:37 +01:00
Christian Schabesberger
8a29567572 merge addExoplayer 2016-03-05 16:54:24 +01:00
Christian Schabesberger
839cd7d1c7 some small fixes 2016-03-05 16:24:47 +01:00
Christian Schabesberger
0bfc7a9177 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-03-05 16:15:00 +01:00
Christian Schabesberger
26e11f96e0 add streamtype field 2016-03-04 15:18:04 +01:00
Christian Schabesberger
86c36acedc removed android code from extractor side 2016-03-04 14:25:37 +01:00
Christian Schabesberger
2318ad2bde changed viewcount notation 2016-03-04 14:16:02 +01:00
Christian Schabesberger
9548dfabd6 made service list do propper error handling 2016-03-04 14:10:41 +01:00
Christian Schabesberger
0c716c12d7 fixed viewcount test again 2016-03-04 13:51:50 +01:00
Weblate
08dd176753 Merge remote-tracking branch 'origin/master' 2016-03-04 13:49:06 +01:00
Thejesh GN
07086bfb3e Translated using Weblate (Kannada)
Currently translated at 30.5% (26 of 85 strings)
2016-03-04 13:49:06 +01:00
Christian Schabesberger
b1d2e64450 ad service_id field, and pulled video/audio stream out of streaminfo 2016-03-04 13:45:41 +01:00
Christian Schabesberger
d9cd928100 fixed audio settings changed bug 2016-03-02 23:23:52 +01:00
naofum
37ec26c8fd Translated using Weblate (Japanese)
Currently translated at 100.0% (85 of 85 strings)
2016-03-02 13:05:54 +01:00
Christian Schabesberger
68b7d9cdff made duration an integer, and made youtubesearch engine throw more parsingexceptions 2016-03-02 02:36:45 +01:00
Christian Schabesberger
3aecd15916 Merge branch 'advancedErrorHandling' 2016-03-02 00:29:56 +01:00
Christian Schabesberger
97d76aee18 fixed failing unit test 2016-03-01 23:54:26 +01:00
Christian Schabesberger
781bf8e7ec fixed yet another bug 2016-03-01 23:28:22 +01:00
Christian Schabesberger
77b9457707 add error handling to suggestions 2016-03-01 18:43:36 +01:00
Christian Schabesberger
1210ab0de0 changed color of snackbar action text 2016-02-29 21:22:16 +01:00
Christian Schabesberger
3c93c4714e fixed crash during crash report 2016-02-29 21:13:02 +01:00
Christian Schabesberger
f90a1ede70 fixed some more bugs 2016-02-29 21:06:00 +01:00
Christian Schabesberger
028354b283 fixed some bugs 2016-02-29 20:33:28 +01:00
Christian Schabesberger
18493a578d made error message be displayed inside erroractivity 2016-02-29 19:23:01 +01:00
Christian Schabesberger
1829dc79c8 make erroractivity handle search engine exceptions 2016-02-29 19:02:40 +01:00
Weblate
7575e8fbe3 Merge remote-tracking branch 'origin/master' 2016-02-29 16:16:54 +01:00
Christian Schabesberger
eed9915c12 add missing gpl3 header to SuggestionListAdapter 2016-02-29 16:19:34 +01:00
Filip Sebastian
be71e45954 Translated using Weblate (Romanian)
Currently translated at 100.0% (72 of 72 strings)
2016-02-29 16:16:54 +01:00
Kamil Modzelewski
3a7978eca0 Translated using Weblate (Polish)
Currently translated at 54.1% (39 of 72 strings)
2016-02-29 16:16:53 +01:00
naofum
c37d2250d4 Translated using Weblate (Japanese)
Currently translated at 100.0% (72 of 72 strings)
2016-02-29 16:16:53 +01:00
Benedikt Freisen
45819d1cd4 Translated using Weblate (German)
Currently translated at 98.6% (71 of 72 strings)
2016-02-29 16:16:53 +01:00
Christian Schabesberger
4ac36af40c made extractor not throw exception upon missing dash mpd 2016-02-29 16:15:15 +01:00
Christian Schabesberger
1a2840b33f made ui handle missing information on search 2016-02-29 16:10:46 +01:00
Christian Schabesberger
d7e75e6011 restructured search engine 2016-02-29 15:59:06 +01:00
Gian Maria Viglianti
73316b87a3 Translated using Weblate (English)
Currently translated at 100.0% (72 of 72 strings)
2016-02-29 03:44:20 +01:00
Matej U
46402691b0 Translated using Weblate (Slovenian)
Currently translated at 100.0% (72 of 72 strings)
2016-02-27 23:05:13 +01:00
Filip Sebastian
e7cef4549f Translated using Weblate (Romanian)
Currently translated at 100.0% (72 of 72 strings)
2016-02-27 17:51:43 +01:00
Christian Schabesberger
737a41f45b display error message 2016-02-27 17:02:38 +01:00
Christian Schabesberger
045ca40a77 renamed video classes to stream classes 2016-02-27 16:37:15 +01:00
Christian Schabesberger
b1fe197c11 changed crashreport email address 2016-02-27 15:57:37 +01:00
Mladen Pejaković
8888530ae3 Translated using Weblate (Serbian)
Currently translated at 100.0% (72 of 72 strings)
2016-02-27 15:34:44 +01:00
Christian Schabesberger
2d51c7428e add ip and timestamp 2016-02-27 15:02:28 +01:00
Christian Schabesberger
863e2a80a2 set errors mail address 2016-02-27 02:26:06 +01:00
Weblate
41d17d2a47 Merge remote-tracking branch 'origin/master' 2016-02-27 02:12:18 +01:00
Christian Schabesberger
36934468d6 uppdate support framework 2016-02-27 02:14:55 +01:00
Thejesh GN
5029ce8728 Translated using Weblate (Kannada)
Currently translated at 1.3% (1 of 72 strings)
2016-02-27 02:12:17 +01:00
Gian Maria Viglianti
e6ab24bcb4 Translated using Weblate (Italian)
Currently translated at 100.0% (72 of 72 strings)
2016-02-27 02:12:17 +01:00
Christian Schabesberger
f3bd263ada new website for newpipe 2016-02-27 02:11:31 +01:00
Gian Maria Viglianti
db7ab3ffce Translated using Weblate (Italian)
Currently translated at 100.0% (72 of 72 strings)
2016-02-27 01:37:42 +01:00
Thejesh GN
85c3755b96 Translated using Weblate (Kannada)
Currently translated at 100% (0 of 0 strings)

Created new translation.
2016-02-26 10:28:11 +01:00
Christian Schabesberger
5decd55551 fixed another pattern problem 2016-02-26 01:42:38 +01:00
Christian Schabesberger
bc468b6f36 fixed stream exception handling 2016-02-26 01:32:44 +01:00
Christian Schabesberger
369d9204d9 add send via mail/share feature 2016-02-25 23:19:43 +01:00
Christian Schabesberger
7caf7be97e add info box 2016-02-25 22:02:42 +01:00
Christian Schabesberger
64c423902a made error handling work a bit 2016-02-25 03:43:13 +01:00
Christian Schabesberger
27a2dee3bd created error report activity 2016-02-24 23:12:02 +01:00
Christian Schabesberger
11d3aeb0dd fixed faling searchengine unittest 2016-02-24 22:36:16 +01:00
Christian Schabesberger
f54d8d318a remove parcelabel from VideoInfoItem 2016-02-24 22:25:51 +01:00
Christian Schabesberger
210f2ef452 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-02-24 22:12:21 +01:00
Christian Schabesberger
d0bab6183a fixed related view 0 view count error 2016-02-24 22:12:13 +01:00
Christian Schabesberger
3441aceba3 fixed viewcount failure 2016-02-24 16:44:46 +01:00
Weblate
0908b9cd76 Merge remote-tracking branch 'origin/master' 2016-02-24 16:42:14 +01:00
vadin
67494ad4c4 Translated using Weblate (Spanish)
Currently translated at 98.6% (71 of 72 strings)
2016-02-24 16:42:14 +01:00
naofum
5d8f75beb4 Translated using Weblate (Japanese)
Currently translated at 100.0% (72 of 72 strings)
2016-02-24 15:06:59 +01:00
Christian Schabesberger
8e7fde99db fix bitcoin qrcode 2016-02-24 13:34:41 +01:00
Christian Schabesberger
bfdf165584 add bitcoin donations 2016-02-24 13:29:53 +01:00
Weblate
9427ebd489 Merge remote-tracking branch 'origin/master' 2016-02-23 23:33:55 +01:00
Christian Schabesberger
e4f753ae82 fixed emty search query on suggestions error 2016-02-23 23:36:02 +01:00
Benedikt Freisen
f2d9d3c2d7 Translated using Weblate (German)
Currently translated at 98.6% (71 of 72 strings)
2016-02-23 23:33:55 +01:00
Nathan Follens
04c5f31cc1 Translated using Weblate (Dutch)
Currently translated at 100.0% (72 of 72 strings)
2016-02-23 23:33:55 +01:00
Matej U
4ea86b714e Translated using Weblate (Slovenian)
Currently translated at 100.0% (72 of 72 strings)
2016-02-23 18:33:20 +01:00
Nathan Follens
cc0b96cba4 Translated using Weblate (Dutch)
Currently translated at 100.0% (72 of 72 strings)
2016-02-23 18:00:54 +01:00
Christian Schabesberger
9e176f8400 Merge branch 'kamadi-master' 2016-02-23 16:52:52 +01:00
Christian Schabesberger
7195ff349b fixed toast issue of the previous commit 2016-02-23 16:42:04 +01:00
Christian Schabesberger
8048ad343e add toast for suggestion error handling 2016-02-23 16:34:14 +01:00
Christian Schabesberger
799a27ec84 Merge branch 'master' of https://github.com/kamadi/NewPipe into kamadi-master 2016-02-23 16:21:16 +01:00
Christian Schabesberger
c7c77ab20c fixed another pattern problem 2016-02-23 15:25:34 +01:00
madiyar
8fc113cc52 Added country language param to the suggestionList method in search engine 2016-02-23 16:22:49 +06:00
madiyar
c7679bec87 Added suggestion to the searching 2016-02-23 15:01:59 +06:00
madiyar
3301d8b4fb Created suggestion adapter 2016-02-23 14:36:24 +06:00
Christian Schabesberger
f5892093a9 made exoplayer work with youtube again 2016-02-23 01:56:04 +01:00
Christian Schabesberger
b06238ba5d initial changes 2016-02-22 20:28:37 +01:00
Christian Schabesberger
dddcc80f30 merged faridk's code 2016-02-22 19:58:04 +01:00
Christian Schabesberger
8854c8c9d0 Merge branch 'master' of github.com:theScrabi/NewPipe 2016-02-22 19:19:22 +01:00
Christian Schabesberger
d02f441eb0 add age restricted material to description 2016-02-22 19:19:13 +01:00
Christian Schabesberger
ff89dd00b6 Merge branch 'rrooij-age_restriction' 2016-02-22 19:18:22 +01:00
Christian Schabesberger
7041e63268 merged age restricted video request 2016-02-22 19:17:05 +01:00
Weblate
8126fdcd15 Merge remote-tracking branch 'origin/master' 2016-02-22 19:16:57 +01:00
Selim
2d61a2f251 Translated using Weblate (Turkish)
Currently translated at 31.8% (22 of 69 strings)
2016-02-22 19:16:57 +01:00
Matej U
7594ee9dbe Translated using Weblate (Slovenian)
Currently translated at 100.0% (69 of 69 strings)
2016-02-22 19:16:56 +01:00
naofum
0862a38599 Translated using Weblate (Japanese)
Currently translated at 100.0% (69 of 69 strings)
2016-02-22 16:37:05 +01:00
Selim
bf7dc462e8 Translated using Weblate (Turkish)
Currently translated at 100% (0 of 0 strings)

Created new translation.
2016-02-22 13:46:14 +01:00
Christian Schabesberger
65b6aaec8e moved on to 0.7.6 2016-02-21 22:57:07 +01:00
Christian Schabesberger
e08aa14eab better detection for livestreams 2016-02-21 22:25:45 +01:00
Christian Schabesberger
851028997a fixed json error from the last commit 2016-02-21 21:15:39 +01:00
Christian Schabesberger
a1479d04df fixed some searchengine errors 2016-02-21 21:08:14 +01:00
rrooij
d12af16f46 VideoItemDetailFragment: check for next vid
Check if the next video is available before loading the thumbnails.
2016-02-21 19:07:24 +01:00
rrooij
2edfcb78fe YTStreamExtractor: implement getAgeRestriction 2016-02-21 18:45:28 +01:00
rrooij
3f0947fa5b Add unit test for restricted YouTube videos 2016-02-21 18:25:18 +01:00
rrooij
d2b808e540 YTStreamExtractor: fix audio tracks on restricted
Fix audio tracks on restriced videos.
2016-02-21 18:24:53 +01:00
Christian Schabesberger
2995a7dc8f actual fix for androi 6.0 notification problem
Notification buttons weren't respondig to clicks. Now they do.
2016-02-21 18:12:00 +01:00
Christian Schabesberger
819db0a30b antifix for android 6.0 notification z order problem 2016-02-21 17:55:00 +01:00
rrooij
4d727245e1 YTStreamExtractor: add support for age restricted
YouTube age restricted videos are now kind of supported. This is not a
final solution to this problem and this commit still crashes because of
some problem with the thumbnail.
2016-02-21 16:39:08 +01:00
Weblate
d8281aeb34 Merge remote-tracking branch 'origin/master' 2016-02-21 01:40:55 +01:00
LelixSuper
cd0f2061b5 Translated using Weblate (Italian)
Currently translated at 100.0% (68 of 68 strings)
2016-02-21 01:40:55 +01:00
Christian Schabesberger
96928d46ca Merge pull request #199 from szafir1100/develop
used regex to delete spaces inside parseLong() argument
2016-02-21 01:40:50 +01:00
LelixSuper
6d55ac2199 Translated using Weblate (Italian)
Currently translated at 100.0% (68 of 68 strings)
2016-02-20 15:16:59 +01:00
Tomasz Marzeion
80dae6ece7 used regex to delete spaces inside parseLong() argument 2016-02-20 13:49:47 +01:00
Farid
3a8611ebf8 Added ExoPlayer support 2016-02-15 18:49:58 -08:00
380 changed files with 21327 additions and 6395 deletions

39
.github/CONTRIBUTING.md vendored Normal file
View File

@@ -0,0 +1,39 @@
NewPipe contribution guidelines
===============================
READ THIS GUIDELINES CAREFULLY BEFORE CONTRIBUTING.
## Crash reporting
Do not report crashes in the GitHub issue tracker. NewPipe has an automated crash report system that will ask you to send a report if a crash occures.
## Issue reporting/feature request
* Search the [existing issues](https://github.com/theScrabi/NewPipe/issues) first to make sure your issue/feature hasn't been reported/requested before
* Check if this issue/feature is already fixed/implemented in the repository
* If you are an android/java developer you are always welcome to fix/implement an issue/a feature yourself
## Bugfixing
* If you want to help NewPipe getting bug free, you can send me a mail to tnp@newpipe.schabi.org to let me know that you intent to help, and than register at our [sentry](https://support.schabi.org) setup.
## Translation
* NewPipe can be translated on [weblate](https://hosted.weblate.org/projects/newpipe/strings/)
## Code contribution
* Stick to NewPipe style guidelines (just look the other code and than do it the same way :) )
* Do not bring nonfree software/binary blobs into the project (keep it google free)
* Stick to [f-droid contribution guidelines](https://f-droid.org/wiki/page/Inclusion_Policy)
* Make changes on a separate branch, not on the master branch (Feature-branching)
* When submitting changes, you agree that your code will be licensed under GPLv3
* Please test (compile and run) your code before you submit changes!!!
* Try to figure out you selves why CI fails, or why a merge request collides
* Please maintain your code after you contributed it.
* Respond yourselves if someone request changes or notifies issues
## Communication
* WE DO NOW HAVE A MAILING LIST: [newpipe@list.schabi.org](https://list.schabi.org/cgi-bin/mailman/listinfo/newpipe).
* If you want to get in contact with me or one of our other contributors you can send me an email at tnp(at)schabi.org
* Feel free to post suggestions, changes, ideas etc!

2
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,2 @@
- [ ] I carefully read the [contribution guidelines](https://github.com/TeamNewPipe/NewPipe/blob/HEAD/.github/CONTRIBUTING.md) and agree to them.
- [ ] I checked if the issue/feature exists in the latest version.

1
.github/PULL_REQUEST_TEAMPLATE.md vendored Normal file
View File

@@ -0,0 +1 @@
[ ] I carefully reed the [contribution guidelines](https://github.com/TeamNewPipe/NewPipe/blob/HEAD/.github/CONTRIBUTING.md) and agree to them.

1
.gitignore vendored
View File

@@ -8,3 +8,4 @@
/.idea
/*.iml
gradle.properties
*~

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "app/src/main/java/org/schabi/newpipe/extractor"]
path = app/src/main/java/org/schabi/newpipe/extractor
url = https://github.com/TeamNewPipe/NewPipeExtractor.git

View File

@@ -1,30 +1,20 @@
language: android
jdk:
- oraclejdk8
android:
components:
# The BuildTools version used by NewPipe
- tools
- build-tools-23.0.2
- build-tools-25.0.0
# The SDK version used to compile NewPipe
- android-23
- android-25
# Additional components
- extra-android-support
- extra-android-m2repository
# Emulators
- sys-img-armeabi-v7a-android-21
- sys-img-armeabi-v7a-android-19
- sys-img-armeabi-v7a-android-15
script: ./gradlew -Dorg.gradle.jvmargs=-Xmx1536m assembleDebug lintDebug testDebugUnitTest
env:
global:
- ADB_INSTALL_TIMEOUT=8 # minutes (2 by default)
matrix:
- ANDROID_TARGET=android-19 ANDROID_ABI=armeabi-v7a
licenses:
- '.+'
before_script:
- echo no | android create avd --force -n test -t $ANDROID_TARGET --abi $ANDROID_ABI
- emulator -avd test -no-skin -no-audio -no-window &
- android-wait-for-emulator
- adb shell input keyevent 82 &

Binary file not shown.

View File

@@ -1,33 +0,0 @@
#Contribution
This document contains guidelines on making contributions to NewPipe.
## Programming
* Follow the [Google Style Guidelines](https://google.github.io/styleguide/javaguide.html)
* Make a new feature on a separate branch, not on the master branch
* Make a [pull request](https://github.com/theScrabi/NewPipe/pulls) if you're done with your changes
* When submitting changes, you agree that your code will be GPLv3 licensed
## Commit messages
* The subject line of your commit message shouldn't be longer than 72 characters
* Try to keep each line of your commit message 72 characters to ensure proper
compatibility with all git tools
* [This guide](http://chris.beams.io/posts/git-commit/) goes more in depth on what makes a good commit message
## Translation
* NewPipe can be translated on [weblate](https://hosted.weblate.org/projects/newpipe/strings/)
## Issue reporting
* Search the [existing issues](https://github.com/theScrabi/NewPipe/issues) first to make sure your issue hasn't been reported before
* Check if this issue is already fixed in the repository
* When making bug reports, be sure to tell which version of NewPipe you are using and the steps to reproduce the problem
* Please include a log if you can
## Communication
* For the time being, [Slack](http://invite.chschtsch.ml/) is being used for project communication
* Feel free to post suggestions, changes, ideas etc!

View File

@@ -1,15 +1,21 @@
WARNING: PUTTING NEWPIPE OR ANY FORK OF IT INTO GOOGLE PLAYSTORE VIOLATES THEIR TERMS OF CONDITIONS.
# NewPipe
NewPipe: A free lightweight Youtube frontend for Android.
[![NewPipe](app/src/main/res/mipmap-xhdpi/ic_launcher.png)](http://dasochan.nl/newpipe/)
[![NewPipe](app/src/main/res/mipmap-xhdpi/ic_launcher.png)](https://newpipe.schabi.org)
[![F-Droid](https://f-droid.org/wiki/images/0/06/F-Droid-button_get-it-on.png)](https://f-droid.org/repository/browse/?fdfilter=newpipe&fdid=org.schabi.newpipe)
Project status:
[![Translation Status](https://hosted.weblate.org/widgets/NewPipe/-/svg-badge.svg)](https://hosted.weblate.org/engage/NewPipe/)
[![Build Status](https://travis-ci.org/theScrabi/NewPipe.svg)](https://travis-ci.org/theScrabi/NewPipe)
[![Build Status](https://travis-ci.org/TeamNewPipe/NewPipe.svg)](https://travis-ci.org/TeamNewPipe/NewPipe)
## Get NewPipe
## Donate
![Bitcoin](https://bitcoin.org/img/icons/logotop.svg)
![BitcoinQR](assets/16A9J59ahMRqkLSZjhYj33n9j3fMztFxnh.png)
[![F-Droid](https://f-droid.org/wiki/images/0/06/F-Droid-button_get-it-on.png)](https://f-droid.org/repository/browse/?fdfilter=newpipe&fdid=org.schabi.newpipe)
`16A9J59ahMRqkLSZjhYj33n9j3fMztFxnh`
## Screenshots
@@ -30,24 +36,28 @@ NewPipe does not use any Google framework libraries, or the YouTube API. It only
* Watch YouTube videos
* Listen to YouTube videos (experimental)
* Select the streaming player to watch the video with
* Download videos (experimental)
* Download audio only (experimental)
* Download videos
* Download audio only
* Open a video in Kodi
* Show Next/Related videos
* Search YouTube in a specific language
* Orbot/Tor support (no streaming yet, experimental)
* Watch age restricted material
* Display general information about channels
* Search channels
* Watch videos from a channel
* Orbot/Tor support (not yet directly)
* 1080p/2k/4k support
### Coming Features
* Improved Downloading
* Bookmarks
* View history
* Search history
* Search channels
* Display general information about channels
* Subscribe to channels
* Watch videos from a channel
* Search/Watch Playlists
* Queeing videos
* Subtitles support
* livestream support
* ... and many more
### Multiservice support
@@ -57,7 +67,7 @@ Although NewPipe only supports YouTube at the moment, it's designed to support m
Whether you have ideas, translation, design changes, code cleaning, or real heavy code changes, help is always welcome.
The more is done the better it gets!
If you'd like to get involved, check our [contribution notes](CONTRIBUTING.md).
If you'd like to get involved, check our [contribution notes](.github/CONTRIBUTING.md).
## License
[![GNU GPLv3 Image](https://www.gnu.org/graphics/gplv3-127x51.png)](http://www.gnu.org/licenses/gpl-3.0.en.html)

View File

@@ -1,15 +1,15 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
applicationId "org.schabi.newpipe"
minSdkVersion 15
targetSdkVersion 23
versionCode 14
versionName "0.7.5"
targetSdkVersion 25
versionCode 30
versionName "0.9.3"
}
buildTypes {
release {
@@ -31,15 +31,22 @@ android {
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
testCompile 'org.json:json:20160810'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'org.jsoup:jsoup:1.8.3'
compile 'org.mozilla:rhino:1.7.7'
compile 'info.guardianproject.netcipher:netcipher:1.2'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.github.nirhart:parallaxscroll:1.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.nononsenseapps:filepicker:3.0.0'
compile 'ch.acra:acra:4.9.0'
compile 'com.google.android.exoplayer:exoplayer:r2.3.1'
}

View File

@@ -1,93 +0,0 @@
package org.schabi.newpipe.services.youtube;
import android.test.AndroidTestCase;
import org.schabi.newpipe.extractor.VideoPreviewInfo;
import org.schabi.newpipe.extractor.SearchEngine;
import org.schabi.newpipe.extractor.services.youtube.YoutubeSearchEngine;
import org.schabi.newpipe.Downloader;
import java.util.ArrayList;
/**
* Created by the-scrabi on 29.12.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* YoutubeSearchEngineTest.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class YoutubeSearchEngineTest extends AndroidTestCase {
private SearchEngine.Result result;
private ArrayList<String> suggestionReply;
@Override
public void setUp() throws Exception{
super.setUp();
SearchEngine engine = new YoutubeSearchEngine();
result = engine.search("https://www.youtube.com/results?search_query=bla",
0, "de", new Downloader());
suggestionReply = engine.suggestionList("hello", new Downloader());
}
public void testIfNoErrorOccur() {
assertEquals(result.errorMessage, "");
}
public void testIfListIsNotEmpty() {
assertEquals(result.resultList.size() > 0, true);
}
public void testItemsHaveTitle() {
for(VideoPreviewInfo i : result.resultList) {
assertEquals(i.title.isEmpty(), false);
}
}
public void testItemsHaveUploader() {
for(VideoPreviewInfo i : result.resultList) {
assertEquals(i.uploader.isEmpty(), false);
}
}
public void testItemsHaveRightDuration() {
for(VideoPreviewInfo i : result.resultList) {
assertTrue(i.duration, i.duration.contains(":"));
}
}
public void testItemsHaveRightThumbnail() {
for (VideoPreviewInfo i : result.resultList) {
assertTrue(i.thumbnail_url, i.thumbnail_url.contains("https://"));
}
}
public void testItemsHaveRightVideoUrl() {
for (VideoPreviewInfo i : result.resultList) {
assertTrue(i.webpage_url, i.webpage_url.contains("https://"));
}
}
public void testIfSuggestionsAreReplied() {
assertEquals(suggestionReply.size() > 0, true);
}
public void testIfSuggestionsAreValid() {
for(String s : suggestionReply) {
assertTrue(s, !s.isEmpty());
}
}
}

View File

@@ -1,39 +1,103 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.schabi.newpipe" >
<uses-permission android:name= "android.permission.INTERNET" />
<uses-permission android:name= "android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
package="org.schabi.newpipe">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:logo="@mipmap/ic_launcher"
android:label="@string/app_name"
android:logo="@mipmap/ic_launcher"
android:theme="@style/AppTheme"
tools:ignore="AllowBackup">
<activity
android:name=".VideoItemListActivity"
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="orientation|screenSize">
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".VideoItemDetailActivity"
android:label="@string/title_videoitem_detail"
android:theme="@style/AppTheme"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".VideoItemListActivity" />
<activity
android:name=".player.PlayVideoActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@style/VideoPlayerTheme"
tools:ignore="UnusedAttribute" />
<service
android:name=".player.BackgroundPlayer"
android:exported="false"
android:label="@string/background_player_name" />
<activity
android:name=".player.MainVideoPlayer"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:label="@string/app_name"
android:launchMode="singleTask"
android:theme="@style/PlayerTheme"/>
<activity
android:name=".settings.SettingsActivity"
android:label="@string/settings_activity_title" />
<activity
android:name=".PanicResponderActivity"
android:launchMode="singleInstance"
android:noHistory="true"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="info.guardianproject.panic.action.TRIGGER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ExitActivity"
android:label="@string/general_error"
android:theme="@android:style/Theme.NoDisplay" />
<activity android:name=".report.ErrorActivity" />
<!-- giga get related -->
<activity
android:name=".download.DownloadActivity"
android:label="@string/app_name"
android:launchMode="singleTask"
android:theme="@style/AppTheme" />
<service android:name="us.shandian.giga.service.DownloadManagerService" />
<activity
android:name="com.nononsenseapps.filepicker.FilePickerActivity"
android:label="@string/app_name"
android:launchMode="singleTop"
android:theme="@style/FilePickerTheme"/>
<activity
android:name=".ReCaptchaActivity"
android:label="@string/reCaptchaActivity" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
<activity
android:name=".RouterActivity"
android:taskAffinity=""
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" />
@@ -47,7 +111,69 @@
<data android:host="youtube.com" />
<data android:host="m.youtube.com" />
<data android:host="www.youtube.com" />
<!-- video prefix -->
<data android:pathPrefix="/v/" />
<data android:pathPrefix="/embed/" />
<data android:pathPrefix="/watch" />
<data android:pathPrefix="/attribution_link" />
<!-- channel prefix -->
<data android:pathPrefix="/channel/"/>
<data android:pathPrefix="/user/"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="youtu.be" />
<data android:pathPrefix="/" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="vnd.youtube" />
<data android:scheme="vnd.youtube.launch" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<activity
android:name=".RouterPopupActivity"
android:taskAffinity=""
android:theme="@android:style/Theme.NoDisplay"
android:label="@string/popup_mode_share_menu_title">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="youtube.com" />
<data android:host="m.youtube.com" />
<data android:host="www.youtube.com" />
<!-- video prefix -->
<data android:pathPrefix="/v/" />
<data android:pathPrefix="/embed/" />
<data android:pathPrefix="/watch" />
<data android:pathPrefix="/attribution_link" />
</intent-filter>
@@ -75,33 +201,15 @@
<data android:scheme="vnd.youtube" />
<data android:scheme="vnd.youtube.launch" />
</intent-filter>
</activity>
<activity android:name=".PlayVideoActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@style/VideoPlayerTheme"
android:parentActivityName=".VideoItemDetailActivity"
tools:ignore="UnusedAttribute">
</activity>
<service
android:name=".BackgroundPlayer"
android:label="@string/background_player_name"
android:exported="false" />
<activity
android:name=".SettingsActivity"
android:label="@string/settings_activity_title" >
</activity>
<activity
android:name=".PanicResponderActivity"
android:launchMode="singleInstance"
android:noHistory="true"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="info.guardianproject.panic.action.TRIGGER" />
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<activity
android:name=".ExitActivity"
android:theme="@android:style/Theme.NoDisplay" />
<service android:name=".player.PopupVideoPlayer"/>
</application>
</manifest>

View File

@@ -20,15 +20,13 @@ package org.schabi.newpipe;
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
import android.graphics.Bitmap;
/**
* Singleton:
* Used to send data between certain Activity/Services within the same process.
* This can be considered as hack inside the Android universe. **/
* This can be considered as an ugly hack inside the Android universe. **/
public class ActivityCommunicator {
private static ActivityCommunicator activityCommunicator = null;
private static ActivityCommunicator activityCommunicator;
public static ActivityCommunicator getCommunicator() {
if(activityCommunicator == null) {
@@ -37,6 +35,5 @@ public class ActivityCommunicator {
return activityCommunicator;
}
// Thumbnail send from VideoItemDetailFragment to BackgroundPlayer
public volatile Bitmap backgroundPlayerThumbnail;
public volatile Class returnActivity;
}

View File

@@ -2,12 +2,20 @@ package org.schabi.newpipe;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import org.acra.ACRA;
import org.acra.config.ACRAConfiguration;
import org.acra.config.ACRAConfigurationException;
import org.acra.config.ConfigurationBuilder;
import org.acra.sender.ReportSenderFactory;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.report.AcraReportSenderFactory;
import org.schabi.newpipe.report.ErrorActivity;
import org.schabi.newpipe.settings.SettingsActivity;
import info.guardianproject.netcipher.NetCipher;
import info.guardianproject.netcipher.proxy.OrbotHelper;
@@ -30,24 +38,46 @@ import info.guardianproject.netcipher.proxy.OrbotHelper;
*/
public class App extends Application {
private static final String TAG = App.class.toString();
private static boolean useTor;
final Class<? extends ReportSenderFactory>[] reportSenderFactoryClasses
= new Class[]{AcraReportSenderFactory.class};
@Override
public void onCreate() {
super.onCreate();
// init crashreport
try {
final ACRAConfiguration acraConfig = new ConfigurationBuilder(this)
.setReportSenderFactoryClasses(reportSenderFactoryClasses)
.build();
ACRA.init(this, acraConfig);
} catch(ACRAConfigurationException ace) {
ace.printStackTrace();
ErrorActivity.reportError(this, ace, null, null,
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,"none",
"Could not initialize ACRA crash report", R.string.app_ui_crash));
}
//init NewPipe
NewPipe.init(Downloader.getInstance());
// Initialize image loader
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(config);
/*
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean(getString(R.string.use_tor_key), false)) {
OrbotHelper.requestStartTor(this);
configureTor(true);
} else {
configureTor(false);
}
}*/
configureTor(false);
// DO NOT REMOVE THIS FUNCTION!!!
// Otherwise downloadPathPreference has invalid value.
@@ -57,7 +87,7 @@ public class App extends Application {
/**
* Set the proxy settings based on whether Tor should be enabled or not.
*/
static void configureTor(boolean enabled) {
public static void configureTor(boolean enabled) {
useTor = enabled;
if (useTor) {
NetCipher.useTor();
@@ -66,13 +96,13 @@ public class App extends Application {
}
}
static void checkStartTor(Context context) {
public static void checkStartTor(Context context) {
if (useTor) {
OrbotHelper.requestStartTor(context);
}
}
static boolean isUsingTor() {
public static boolean isUsingTor() {
return useTor;
}
}

View File

@@ -1,335 +0,0 @@
package org.schabi.newpipe;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.io.IOException;
/**
* Created by Adam Howard on 08/11/15.
* Copyright (c) Adam Howard <achdisposable1@gmail.com> 2015
*
* BackgroundPlayer.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
/**Plays the audio stream of videos in the background.*/
public class BackgroundPlayer extends Service /*implements MediaPlayer.OnPreparedListener*/ {
private static final String TAG = BackgroundPlayer.class.toString();
private static final String ACTION_STOP = TAG + ".STOP";
private static final String ACTION_PLAYPAUSE = TAG + ".PLAYPAUSE";
// Extra intent arguments
public static final String TITLE = "title";
public static final String WEB_URL = "web_url";
public static final String SERVICE_ID = "service_id";
public static final String CHANNEL_NAME = "channel_name";
private volatile String webUrl = "";
private volatile int serviceId = -1;
private volatile String channelName = "";
// Determines if the service is already running.
// Prevents launching the service twice.
public static volatile boolean isRunning = false;
public BackgroundPlayer() {
super();
}
@Override
public void onCreate() {
/*PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);*/
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, R.string.background_player_playing_toast,
Toast.LENGTH_SHORT).show();
String source = intent.getDataString();
//Log.i(TAG, "backgroundPLayer source:"+source);
String videoTitle = intent.getStringExtra(TITLE);
webUrl = intent.getStringExtra(WEB_URL);
serviceId = intent.getIntExtra(SERVICE_ID, -1);
channelName = intent.getStringExtra(CHANNEL_NAME);
//do nearly everything in a separate thread
PlayerThread player = new PlayerThread(source, videoTitle, this);
player.start();
isRunning = true;
// If we get killed after returning here, don't restart
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding (yet?), so return null
return null;
}
@Override
public void onDestroy() {
//Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
isRunning = false;
}
private class PlayerThread extends Thread {
MediaPlayer mediaPlayer;
private String source;
private String title;
private int noteID = TAG.hashCode();
private BackgroundPlayer owner;
private NotificationManager noteMgr;
private WifiManager.WifiLock wifiLock;
private Bitmap videoThumbnail = null;
private NotificationCompat.Builder noteBuilder;
private Notification note;
public PlayerThread(String src, String title, BackgroundPlayer owner) {
this.source = src;
this.title = title;
this.owner = owner;
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
@Override
public void run() {
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);//cpu lock
try {
mediaPlayer.setDataSource(source);
//We are already in a separate worker thread,
//so calling the blocking prepare() method should be ok
mediaPlayer.prepare();
} catch (IOException ioe) {
ioe.printStackTrace();
Log.e(TAG, "video source:" + source);
Log.e(TAG, "video title:" + title);
//can't do anything useful without a file to play; exit early
return;
}
try {
videoThumbnail = ActivityCommunicator.getCommunicator().backgroundPlayerThumbnail;
} catch (Exception e) {
Log.e(TAG, "Could not get video thumbnail from ActivityCommunicator");
e.printStackTrace();
}
WifiManager wifiMgr = ((WifiManager)getSystemService(Context.WIFI_SERVICE));
wifiLock = wifiMgr.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG);
//listen for end of video
mediaPlayer.setOnCompletionListener(new EndListener(wifiLock));
//get audio focus
/*
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// could not get audio focus.
}*/
wifiLock.acquire();
mediaPlayer.start();
IntentFilter filter = new IntentFilter();
filter.setPriority(Integer.MAX_VALUE);
filter.addAction(ACTION_PLAYPAUSE);
filter.addAction(ACTION_STOP);
registerReceiver(broadcastReceiver, filter);
note = buildNotification();
startForeground(noteID, note);
//currently decommissioned progressbar looping update code - works, but doesn't fit inside
//Notification.MediaStyle Notification layout.
noteMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
/*
//update every 2s or 4 times in the video, whichever is shorter
int sleepTime = Math.min(2000, (int)((double)vidLength/4));
while(mediaPlayer.isPlaying()) {
noteBuilder.setProgress(vidLength, mediaPlayer.getCurrentPosition(), false);
noteMgr.notify(noteID, noteBuilder.build());
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Log.d(TAG, "sleep failure");
}
}*/
}
/**Handles button presses from the notification. */
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Log.i(TAG, "received broadcast action:"+action);
if(action.equals(ACTION_PLAYPAUSE)) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
note.contentView.setImageViewResource(R.id.notificationPlayPause, R.drawable.ic_play_circle_filled_white_24dp);
if(android.os.Build.VERSION.SDK_INT >=16){
note.bigContentView.setImageViewResource(R.id.notificationPlayPause, R.drawable.ic_play_circle_filled_white_24dp);
}
noteMgr.notify(noteID, note);
}
else {
//reacquire CPU lock after auto-releasing it on pause
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.start();
note.contentView.setImageViewResource(R.id.notificationPlayPause, R.drawable.ic_pause_white_24dp);
if(android.os.Build.VERSION.SDK_INT >=16){
note.bigContentView.setImageViewResource(R.id.notificationPlayPause, R.drawable.ic_pause_white_24dp);
}
noteMgr.notify(noteID, note);
}
}
else if(action.equals(ACTION_STOP)) {
//this auto-releases CPU lock
mediaPlayer.stop();
afterPlayCleanup();
}
}
};
private void afterPlayCleanup() {
//remove progress bar
//noteBuilder.setProgress(0, 0, false);
//remove notification
noteMgr.cancel(noteID);
unregisterReceiver(broadcastReceiver);
//release mediaPlayer's system resources
mediaPlayer.release();
//release wifilock
wifiLock.release();
//remove foreground status of service; make BackgroundPlayer killable
stopForeground(true);
stopSelf();
}
private class EndListener implements MediaPlayer.OnCompletionListener {
private WifiManager.WifiLock wl;
public EndListener(WifiManager.WifiLock wifiLock) {
this.wl = wifiLock;
}
@Override
public void onCompletion(MediaPlayer mp) {
afterPlayCleanup();
}
}
private Notification buildNotification() {
Notification note;
Resources res = getApplicationContext().getResources();
noteBuilder = new NotificationCompat.Builder(owner);
PendingIntent playPI = PendingIntent.getBroadcast(owner, noteID,
new Intent(ACTION_PLAYPAUSE), PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent stopPI = PendingIntent.getBroadcast(owner, noteID,
new Intent(ACTION_STOP), PendingIntent.FLAG_UPDATE_CURRENT);
/*
NotificationCompat.Action pauseButton = new NotificationCompat.Action.Builder
(R.drawable.ic_pause_white_24dp, "Pause", playPI).build();
*/
//build intent to return to video, on tapping notification
Intent openDetailViewIntent = new Intent(getApplicationContext(),
VideoItemDetailActivity.class);
openDetailViewIntent.putExtra(VideoItemDetailFragment.STREAMING_SERVICE, serviceId);
openDetailViewIntent.putExtra(VideoItemDetailFragment.VIDEO_URL, webUrl);
openDetailViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent openDetailView = PendingIntent.getActivity(owner, noteID,
openDetailViewIntent, PendingIntent.FLAG_UPDATE_CURRENT);
noteBuilder
.setOngoing(true)
.setDeleteIntent(stopPI)
//doesn't fit with Notification.MediaStyle
//.setProgress(vidLength, 0, false)
.setSmallIcon(R.drawable.ic_play_circle_filled_white_24dp)
.setTicker(
String.format(res.getString(
R.string.background_player_time_text), title))
.setContentIntent(PendingIntent.getActivity(getApplicationContext(),
noteID, openDetailViewIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
RemoteViews view =
new RemoteViews(BuildConfig.APPLICATION_ID, R.layout.player_notification);
view.setImageViewBitmap(R.id.notificationCover, videoThumbnail);
view.setTextViewText(R.id.notificationSongName, title);
view.setTextViewText(R.id.notificationArtist, channelName);
view.setOnClickPendingIntent(R.id.notificationStop, stopPI);
view.setOnClickPendingIntent(R.id.notificationPlayPause, playPI);
view.setOnClickPendingIntent(R.id.notificationBackgroundButton, openDetailView);
//possibly found the expandedView problem,
//but can't test it as I don't have a 5.0 device. -medavox
RemoteViews expandedView =
new RemoteViews(BuildConfig.APPLICATION_ID, R.layout.player_notification_expanded);
expandedView.setImageViewBitmap(R.id.notificationCover, videoThumbnail);
expandedView.setTextViewText(R.id.notificationSongName, title);
expandedView.setTextViewText(R.id.notificationArtist, channelName);
expandedView.setOnClickPendingIntent(R.id.notificationStop, stopPI);
expandedView.setOnClickPendingIntent(R.id.notificationPlayPause, playPI);
expandedView.setOnClickPendingIntent(R.id.notificationBackgroundButton, openDetailView);
noteBuilder.setCategory(Notification.CATEGORY_TRANSPORT);
//Make notification appear on lockscreen
noteBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
note = noteBuilder.build();
note.contentView = view;
if (android.os.Build.VERSION.SDK_INT > 16) {
note.bigContentView = expandedView;
}
return note;
}
}
}

View File

@@ -1,190 +0,0 @@
package org.schabi.newpipe;
import android.Manifest;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Christian Schabesberger on 21.09.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* DownloadDialog.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class DownloadDialog extends DialogFragment {
private static final String TAG = DialogFragment.class.getName();
public static final String TITLE = "name";
public static final String FILE_SUFFIX_AUDIO = "file_suffix_audio";
public static final String FILE_SUFFIX_VIDEO = "file_suffix_video";
public static final String AUDIO_URL = "audio_url";
public static final String VIDEO_URL = "video_url";
private Bundle arguments;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
arguments = getArguments();
super.onCreateDialog(savedInstanceState);
if(ContextCompat.checkSelfPermission(this.getContext(),Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.download_dialog_title);
// If no audio stream available
if(arguments.getString(AUDIO_URL) == null) {
builder.setItems(R.array.download_options_no_audio, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Context context = getActivity();
String title = arguments.getString(TITLE);
switch (which) {
case 0: // Video
download(arguments.getString(VIDEO_URL),
title,
arguments.getString(FILE_SUFFIX_VIDEO), context);
break;
default:
Log.d(TAG, "lolz");
}
}
});
// If no video stream available
} else if(arguments.getString(VIDEO_URL) == null) {
builder.setItems(R.array.download_options_no_video, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Context context = getActivity();
String title = arguments.getString(TITLE);
switch (which) {
case 0: // Audio
download(arguments.getString(AUDIO_URL),
title,
arguments.getString(FILE_SUFFIX_AUDIO), context);
break;
default:
Log.d(TAG, "lolz");
}
}
});
//if both streams ar available
} else {
builder.setItems(R.array.download_options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Context context = getActivity();
String title = arguments.getString(TITLE);
switch (which) {
case 0: // Video
download(arguments.getString(VIDEO_URL),
title,
arguments.getString(FILE_SUFFIX_VIDEO), context);
break;
case 1:
download(arguments.getString(AUDIO_URL),
title,
arguments.getString(FILE_SUFFIX_AUDIO), context);
break;
default:
Log.d(TAG, "lolz");
}
}
});
}
return builder.create();
}
/**
* #143 #44 #42 #22: make shure that the filename does not contain illegal chars.
* This should fix some of the "cannot download" problems.
* */
private String createFileName(String fName) {
// from http://eng-przemelek.blogspot.de/2009/07/how-to-create-valid-file-name.html
List<String> forbiddenCharsPatterns = new ArrayList<String> ();
forbiddenCharsPatterns.add("[:]+"); // Mac OS, but it looks that also Windows XP
forbiddenCharsPatterns.add("[\\*\"/\\\\\\[\\]\\:\\;\\|\\=\\,]+"); // Windows
forbiddenCharsPatterns.add("[^\\w\\d\\.]+"); // last chance... only latin letters and digits
String nameToTest = fName;
for (String pattern : forbiddenCharsPatterns) {
nameToTest = nameToTest.replaceAll(pattern, "_");
}
return nameToTest;
}
private void download(String url, String title, String fileSuffix, Context context) {
File downloadDir = NewPipeSettings.getDownloadFolder();
if(!downloadDir.exists()) {
//attempt to create directory
boolean mkdir = downloadDir.mkdirs();
if(!mkdir && !downloadDir.isDirectory()) {
String message = context.getString(R.string.err_dir_create,downloadDir.toString());
Log.e(TAG, message);
Toast.makeText(context,message , Toast.LENGTH_LONG).show();
return;
}
String message = context.getString(R.string.info_dir_created,downloadDir.toString());
Log.e(TAG, message);
Toast.makeText(context,message , Toast.LENGTH_LONG).show();
}
File saveFilePath = new File(downloadDir,createFileName(title) + fileSuffix);
long id = 0;
if (App.isUsingTor()) {
// if using Tor, do not use DownloadManager because the proxy cannot be set
FileDownloader.downloadFile(getContext(), url, saveFilePath, title);
} else {
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setDestinationUri(Uri.fromFile(saveFilePath));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle(title);
request.setDescription("'" + url +
"' => '" + saveFilePath + "'");
request.allowScanningByMediaScanner();
try {
id = dm.enqueue(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Log.i(TAG,"Started downloading '" + url +
"' => '" + saveFilePath + "' #" + id);
}
}

View File

@@ -1,14 +1,18 @@
package org.schabi.newpipe;
import org.schabi.newpipe.extractor.exceptions.ReCaptchaException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import info.guardianproject.netcipher.NetCipher;
/**
* Created by Christian Schabesberger on 28.01.16.
@@ -33,22 +37,62 @@ import info.guardianproject.netcipher.NetCipher;
public class Downloader implements org.schabi.newpipe.extractor.Downloader {
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0";
private static String mCookies = "";
private static Downloader instance = null;
private Downloader() {}
public static Downloader getInstance() {
if(instance == null) {
synchronized (Downloader.class) {
if (instance == null) {
instance = new Downloader();
}
}
}
return instance;
}
public static synchronized void setCookies(String cookies) {
Downloader.mCookies = cookies;
}
public static synchronized String getCookies() {
return Downloader.mCookies;
}
/**Download the text file at the supplied URL as in download(String),
* but set the HTTP header field "Accept-Language" to the supplied string.
* @param siteUrl the URL of the text file to return the contents of
* @param language the language (usually a 2-character code) to set as the preferred language
* @return the contents of the specified text file*/
public String download(String siteUrl, String language) throws IOException {
public String download(String siteUrl, String language) throws IOException, ReCaptchaException {
Map<String, String> requestProperties = new HashMap<>();
requestProperties.put("Accept-Language", language);
return download(siteUrl, requestProperties);
}
/**Download the text file at the supplied URL as in download(String),
* but set the HTTP header field "Accept-Language" to the supplied string.
* @param siteUrl the URL of the text file to return the contents of
* @param customProperties set request header properties
* @return the contents of the specified text file
* @throws IOException*/
public String download(String siteUrl, Map<String, String> customProperties) throws IOException, ReCaptchaException {
URL url = new URL(siteUrl);
//HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
HttpsURLConnection con = NetCipher.getHttpsURLConnection(url);
con.setRequestProperty("Accept-Language", language);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
Iterator it = customProperties.entrySet().iterator();
while(it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
con.setRequestProperty((String)pair.getKey(), (String)pair.getValue());
}
return dl(con);
}
/**Common functionality between download(String url) and download(String url, String language)*/
private static String dl(HttpsURLConnection con) throws IOException {
private static String dl(HttpsURLConnection con) throws IOException, ReCaptchaException {
StringBuilder response = new StringBuilder();
BufferedReader in = null;
@@ -56,6 +100,10 @@ public class Downloader implements org.schabi.newpipe.extractor.Downloader {
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
if (getCookies().length() > 0) {
con.setRequestProperty("Cookie", getCookies());
}
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
@@ -67,6 +115,14 @@ public class Downloader implements org.schabi.newpipe.extractor.Downloader {
throw new IOException("unknown host or no network", uhe);
//Toast.makeText(getActivity(), uhe.getMessage(), Toast.LENGTH_LONG).show();
} catch(Exception e) {
/*
* HTTP 429 == Too Many Request
* Receive from Youtube.com = ReCaptcha challenge request
* See : https://github.com/rg3/youtube-dl/issues/5138
*/
if (con.getResponseCode() == 429) {
throw new ReCaptchaException("reCaptcha Challenge requested");
}
throw new IOException(e);
} finally {
if(in != null) {
@@ -81,7 +137,7 @@ public class Downloader implements org.schabi.newpipe.extractor.Downloader {
* Primarily intended for downloading web pages.
* @param siteUrl the URL of the text file to download
* @return the contents of the specified text file*/
public String download(String siteUrl) throws IOException {
public String download(String siteUrl) throws IOException, ReCaptchaException {
URL url = new URL(siteUrl);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
//HttpsURLConnection con = NetCipher.getHttpsURLConnection(url);

View File

@@ -0,0 +1,64 @@
package org.schabi.newpipe;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.report.ErrorActivity;
/**
* Created by Christian Schabesberger on 01.08.16.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* StreamInfoItemViewCreator.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class ImageErrorLoadingListener implements ImageLoadingListener {
private int serviceId = -1;
private Context context = null;
private View rootView = null;
public ImageErrorLoadingListener(Context context, View rootView, int serviceId) {
this.context = context;
this.serviceId= serviceId;
this.rootView = rootView;
}
@Override
public void onLoadingStarted(String imageUri, View view) {}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
ErrorActivity.reportError(context,
failReason.getCause(), null, rootView,
ErrorActivity.ErrorInfo.make(ErrorActivity.LOAD_IMAGE,
NewPipe.getNameOfService(serviceId), imageUri,
R.string.could_not_load_image));
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
}
@Override
public void onLoadingCancelled(String imageUri, View view) {}
}

View File

@@ -34,6 +34,9 @@ import java.util.Locale;
public class Localization {
private Localization() {
}
public static Locale getPreferredLocale(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

View File

@@ -0,0 +1,249 @@
/*
* Created by Christian Schabesberger on 02.08.16.
* <p>
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* DownloadActivity.java is part of NewPipe.
* <p>
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.schabi.newpipe;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.schabi.newpipe.download.DownloadActivity;
import org.schabi.newpipe.extractor.StreamingService;
import org.schabi.newpipe.fragments.OnItemSelectedListener;
import org.schabi.newpipe.fragments.channel.ChannelFragment;
import org.schabi.newpipe.fragments.detail.VideoDetailFragment;
import org.schabi.newpipe.fragments.search.SearchFragment;
import org.schabi.newpipe.settings.SettingsActivity;
import org.schabi.newpipe.util.Constants;
import org.schabi.newpipe.util.NavigationHelper;
import org.schabi.newpipe.util.PermissionHelper;
import org.schabi.newpipe.util.ThemeHelper;
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener {
//private static final String TAG = "MainActivity";
/*//////////////////////////////////////////////////////////////////////////
// Activity's LifeCycle
//////////////////////////////////////////////////////////////////////////*/
@Override
protected void onCreate(Bundle savedInstanceState) {
ThemeHelper.setTheme(this, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (getSupportFragmentManager() != null && getSupportFragmentManager().getBackStackEntryCount() == 0) {
initFragments();
}
}
@Override
protected void onNewIntent(Intent intent) {
if (intent != null) {
// Return if launched from a launcher (e.g. Nova Launcher, Pixel Launcher ...)
// to not destroy the already created backstack
String action = intent.getAction();
if ((action != null && action.equals(Intent.ACTION_MAIN)) && intent.hasCategory(Intent.CATEGORY_LAUNCHER)) return;
}
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
@Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_holder);
if (fragment instanceof VideoDetailFragment) if (((VideoDetailFragment) fragment).onActivityBackPressed()) return;
if (getSupportFragmentManager().getBackStackEntryCount() >= 2) {
getSupportFragmentManager().popBackStackImmediate();
} else {
if (fragment instanceof SearchFragment) {
SearchFragment searchFragment = (SearchFragment) fragment;
if (!searchFragment.isMainBgVisible()) {
getSupportFragmentManager().beginTransaction().remove(fragment).commitNow();
NavigationHelper.openMainActivity(this);
return;
}
}
finish();
}
}
/*//////////////////////////////////////////////////////////////////////////
// Menu
//////////////////////////////////////////////////////////////////////////*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home: {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_holder);
if (fragment instanceof VideoDetailFragment) ((VideoDetailFragment) fragment).clearHistory();
NavigationHelper.openMainActivity(this);
return true;
}
case R.id.action_settings: {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
case R.id.action_show_downloads: {
if (!PermissionHelper.checkStoragePermissions(this)) {
return false;
}
Intent intent = new Intent(this, DownloadActivity.class);
startActivity(intent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
/*//////////////////////////////////////////////////////////////////////////
// Init
//////////////////////////////////////////////////////////////////////////*/
private void initFragments() {
if (getIntent() != null && getIntent().hasExtra(Constants.KEY_URL)) {
handleIntent(getIntent());
} else openSearchFragment();
}
/*//////////////////////////////////////////////////////////////////////////
// OnItemSelectedListener
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onItemSelected(StreamingService.LinkType linkType, int serviceId, String url, String name) {
switch (linkType) {
case STREAM:
openVideoDetailFragment(serviceId, url, name, false);
break;
case CHANNEL:
openChannelFragment(serviceId, url, name);
break;
}
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
private void handleIntent(Intent intent) {
if (intent.hasExtra(Constants.KEY_LINK_TYPE)) {
String url = intent.getStringExtra(Constants.KEY_URL);
int serviceId = intent.getIntExtra(Constants.KEY_SERVICE_ID, 0);
try {
switch (((StreamingService.LinkType) intent.getSerializableExtra(Constants.KEY_LINK_TYPE))) {
case STREAM:
handleVideoDetailIntent(serviceId, url, intent);
break;
case CHANNEL:
handleChannelIntent(serviceId, url, intent);
break;
case NONE:
throw new Exception("Url not known to service. service=" + Integer.toString(serviceId) + " url=" + url);
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
openSearchFragment();
}
}
private void openSearchFragment() {
ImageLoader.getInstance().clearMemoryCache();
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.fragment_holder, new SearchFragment())
.addToBackStack(null)
.commit();
}
private void openVideoDetailFragment(int serviceId, String url, String title, boolean autoPlay) {
ImageLoader.getInstance().clearMemoryCache();
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_holder);
if (title == null) title = "";
if (fragment instanceof VideoDetailFragment && fragment.isVisible()) {
VideoDetailFragment detailFragment = (VideoDetailFragment) fragment;
detailFragment.setAutoplay(autoPlay);
detailFragment.selectAndLoadVideo(serviceId, url, title);
return;
}
VideoDetailFragment instance = VideoDetailFragment.getInstance(serviceId, url, title);
instance.setAutoplay(autoPlay);
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.fragment_holder, instance)
.addToBackStack(null)
.commit();
}
private void openChannelFragment(int serviceId, String url, String name) {
ImageLoader.getInstance().clearMemoryCache();
if (name == null) name = "";
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.fragment_holder, ChannelFragment.newInstance(serviceId, url, name))
.addToBackStack(null)
.commit();
}
private void handleVideoDetailIntent(int serviceId, String url, Intent intent) {
boolean autoPlay = intent.getBooleanExtra(VideoDetailFragment.AUTO_PLAY, false);
String title = intent.getStringExtra(Constants.KEY_TITLE);
openVideoDetailFragment(serviceId, url, title, autoPlay);
}
private void handleChannelIntent(int serviceId, String url, Intent intent) {
String name = intent.getStringExtra(Constants.KEY_TITLE);
openChannelFragment(serviceId, url, name);
}
}

View File

@@ -0,0 +1,151 @@
package org.schabi.newpipe;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Created by beneth <bmauduit@beneth.fr> on 06.12.16.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* ReCaptchaActivity.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class ReCaptchaActivity extends AppCompatActivity {
public static final int RECAPTCHA_REQUEST = 10;
public static final String TAG = ReCaptchaActivity.class.toString();
public static final String YT_URL = "https://www.youtube.com";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recaptcha);
// Set return to Cancel by default
setResult(RESULT_CANCELED);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.reCaptcha_title);
actionBar.setDisplayShowTitleEnabled(true);
WebView myWebView = (WebView) findViewById(R.id.reCaptchaWebView);
// Enable Javascript
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
ReCaptchaWebViewClient webClient = new ReCaptchaWebViewClient(this);
myWebView.setWebViewClient(webClient);
// Cleaning cache, history and cookies from webView
myWebView.clearCache(true);
myWebView.clearHistory();
android.webkit.CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
@Override
public void onReceiveValue(Boolean aBoolean) {}
});
} else {
cookieManager.removeAllCookie();
}
myWebView.loadUrl(YT_URL);
}
private class ReCaptchaWebViewClient extends WebViewClient {
private Activity context;
private String mCookies;
ReCaptchaWebViewClient(Activity ctx) {
context = ctx;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO: Start Loader
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
String cookies = CookieManager.getInstance().getCookie(url);
// TODO: Stop Loader
// find cookies : s_gl & goojf and Add cookies to Downloader
if (find_access_cookies(cookies)) {
// Give cookies to Downloader class
Downloader.setCookies(mCookies);
// Closing activity and return to parent
setResult(RESULT_OK);
finish();
}
}
private boolean find_access_cookies(String cookies) {
boolean ret = false;
String c_s_gl = "";
String c_goojf = "";
String[] parts = cookies.split("; ");
for (String part : parts) {
if (part.trim().startsWith("s_gl")) {
c_s_gl = part.trim();
}
if (part.trim().startsWith("goojf")) {
c_goojf = part.trim();
}
}
if (c_s_gl.length() > 0 && c_goojf.length() > 0) {
ret = true;
//mCookies = c_s_gl + "; " + c_goojf;
// Youtube seems to also need the other cookies:
mCookies = cookies;
}
return ret;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home: {
Intent intent = new Intent(this, org.schabi.newpipe.MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, intent);
return true;
}
default:
return false;
}
}
}

View File

@@ -0,0 +1,124 @@
package org.schabi.newpipe;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import org.schabi.newpipe.util.NavigationHelper;
import java.util.Collection;
import java.util.HashSet;
/*
* Copyright (C) Christian Schabesberger 2017 <chris.schabesberger@mailbox.org>
* RouterActivity .java is part of NewPipe.
*
* OpenHitboxStreams is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenHitboxStreams is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenHitboxStreams. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This Acitivty is designed to route share/open intents to the specified service, and
* to the part of the service which can handle the url.
*/
public class RouterActivity extends Activity {
//private static final String TAG = "RouterActivity"
/**
* Removes invisible separators (\p{Z}) and punctuation characters including
* brackets (\p{P}). See http://www.regular-expressions.info/unicode.html for
* more details.
*/
private final static String REGEX_REMOVE_FROM_URL = "[\\p{Z}\\p{P}]";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleIntent(getIntent());
finish();
}
private void handleIntent(Intent intent) {
String videoUrl = "";
// first gather data and find service
if (intent.getData() != null) {
// this means the video was called though another app
videoUrl = intent.getData().toString();
} else if (intent.getStringExtra(Intent.EXTRA_TEXT) != null) {
//this means that vidoe was called through share menu
String extraText = intent.getStringExtra(Intent.EXTRA_TEXT);
videoUrl = getUris(extraText)[0];
}
try {
NavigationHelper.openByLink(this, videoUrl);
} catch (Exception e) {
Toast.makeText(this, R.string.url_not_supported_toast, Toast.LENGTH_LONG).show();
}
}
private static String removeHeadingGibberish(final String input) {
int start = 0;
for (int i = input.indexOf("://") - 1; i >= 0; i--) {
if (!input.substring(i, i + 1).matches("\\p{L}")) {
start = i + 1;
break;
}
}
return input.substring(start, input.length());
}
private static String trim(final String input) {
if (input == null || input.length() < 1) {
return input;
} else {
String output = input;
while (output.length() > 0 && output.substring(0, 1).matches(REGEX_REMOVE_FROM_URL)) {
output = output.substring(1);
}
while (output.length() > 0
&& output.substring(output.length() - 1, output.length()).matches(REGEX_REMOVE_FROM_URL)) {
output = output.substring(0, output.length() - 1);
}
return output;
}
}
/**
* Retrieves all Strings which look remotely like URLs from a text.
* Used if NewPipe was called through share menu.
*
* @param sharedText text to scan for URLs.
* @return potential URLs
*/
private String[] getUris(final String sharedText) {
final Collection<String> result = new HashSet<>();
if (sharedText != null) {
final String[] array = sharedText.split("\\p{Space}");
for (String s : array) {
s = trim(s);
if (s.length() != 0) {
if (s.matches(".+://.+")) {
result.add(removeHeadingGibberish(s));
} else if (s.matches(".+\\..+")) {
result.add("http://" + s);
}
}
}
}
return result.toArray(new String[result.size()]);
}
}

View File

@@ -0,0 +1,130 @@
package org.schabi.newpipe;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.extractor.StreamingService;
import org.schabi.newpipe.player.PopupVideoPlayer;
import org.schabi.newpipe.util.Constants;
import org.schabi.newpipe.util.PermissionHelper;
import java.util.Collection;
import java.util.HashSet;
/**
* This activity is thought to open video streams form an external app using the popup player.
*/
public class RouterPopupActivity extends Activity {
//private static final String TAG = "RouterPopupActivity";
/**
* Removes invisible separators (\p{Z}) and punctuation characters including
* brackets (\p{P}). See http://www.regular-expressions.info/unicode.html for
* more details.
*/
private final static String REGEX_REMOVE_FROM_URL = "[\\p{Z}\\p{P}]";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleIntent(getIntent());
finish();
}
private void handleIntent(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !PermissionHelper.checkSystemAlertWindowPermission(this)) {
Toast.makeText(this, R.string.msg_popup_permission, Toast.LENGTH_LONG).show();
return;
}
String videoUrl = "";
StreamingService service;
// first gather data and find service
if (intent.getData() != null) {
// this means the video was called though another app
videoUrl = intent.getData().toString();
} else if (intent.getStringExtra(Intent.EXTRA_TEXT) != null) {
//this means that vidoe was called through share menu
String extraText = intent.getStringExtra(Intent.EXTRA_TEXT);
videoUrl = getUris(extraText)[0];
}
service = NewPipe.getServiceByUrl(videoUrl);
if (service == null) {
Toast.makeText(this, R.string.url_not_supported_toast, Toast.LENGTH_LONG).show();
return;
}
Intent callIntent = new Intent(this, PopupVideoPlayer.class);
switch (service.getLinkTypeByUrl(videoUrl)) {
case STREAM:
break;
default:
Toast.makeText(this, R.string.url_not_supported_toast, Toast.LENGTH_LONG).show();
return;
}
callIntent.putExtra(Constants.KEY_URL, videoUrl);
callIntent.putExtra(Constants.KEY_SERVICE_ID, service.getServiceId());
startService(callIntent);
}
private static String removeHeadingGibberish(final String input) {
int start = 0;
for (int i = input.indexOf("://") - 1; i >= 0; i--) {
if (!input.substring(i, i + 1).matches("\\p{L}")) {
start = i + 1;
break;
}
}
return input.substring(start, input.length());
}
private static String trim(final String input) {
if (input == null || input.length() < 1) {
return input;
} else {
String output = input;
while (output.length() > 0 && output.substring(0, 1).matches(REGEX_REMOVE_FROM_URL)) {
output = output.substring(1);
}
while (output.length() > 0
&& output.substring(output.length() - 1, output.length()).matches(REGEX_REMOVE_FROM_URL)) {
output = output.substring(0, output.length() - 1);
}
return output;
}
}
/**
* Retrieves all Strings which look remotely like URLs from a text.
* Used if NewPipe was called through share menu.
*
* @param sharedText text to scan for URLs.
* @return potential URLs
*/
private String[] getUris(final String sharedText) {
final Collection<String> result = new HashSet<>();
if (sharedText != null) {
final String[] array = sharedText.split("\\p{Space}");
for (String s : array) {
s = trim(s);
if (s.length() != 0) {
if (s.matches(".+://.+")) {
result.add(removeHeadingGibberish(s));
} else if (s.matches(".+\\..+")) {
result.add("http://" + s);
}
}
}
}
return result.toArray(new String[result.size()]);
}
}

View File

@@ -1,260 +0,0 @@
package org.schabi.newpipe;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import info.guardianproject.netcipher.proxy.OrbotHelper;
/**
* Created by Christian Schabesberger on 31.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* SettingsActivity.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class SettingsActivity extends PreferenceActivity {
private static final int REQUEST_INSTALL_ORBOT = 0x1234;
private AppCompatDelegate mDelegate = null;
@Override
protected void onCreate(Bundle savedInstanceBundle) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceBundle);
super.onCreate(savedInstanceBundle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragment{
SharedPreferences.OnSharedPreferenceChangeListener prefListener;
// get keys
String DEFAULT_RESOLUTION_PREFERENCE;
String DEFAULT_AUDIO_FORMAT_PREFERENCE;
String SEARCH_LANGUAGE_PREFERENCE;
String DOWNLOAD_PATH_PREFERENCE;
String DOWNLOAD_PATH_AUDIO_PREFERENCE;
String USE_TOR_KEY;
private ListPreference defaultResolutionPreference;
private ListPreference defaultAudioFormatPreference;
private ListPreference searchLanguagePreference;
private EditTextPreference downloadPathPreference;
private EditTextPreference downloadPathAudioPreference;
private CheckBoxPreference useTorCheckBox;
private SharedPreferences defaultPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
final Activity activity = getActivity();
defaultPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
// get keys
DEFAULT_RESOLUTION_PREFERENCE =getString(R.string.default_resolution_key);
DEFAULT_AUDIO_FORMAT_PREFERENCE =getString(R.string.default_audio_format_key);
SEARCH_LANGUAGE_PREFERENCE =getString(R.string.search_language_key);
DOWNLOAD_PATH_PREFERENCE = getString(R.string.download_path_key);
DOWNLOAD_PATH_AUDIO_PREFERENCE = getString(R.string.download_path_audio_key);
USE_TOR_KEY = getString(R.string.use_tor_key);
// get pref objects
defaultResolutionPreference =
(ListPreference) findPreference(DEFAULT_RESOLUTION_PREFERENCE);
defaultAudioFormatPreference =
(ListPreference) findPreference(DEFAULT_AUDIO_FORMAT_PREFERENCE);
searchLanguagePreference =
(ListPreference) findPreference(SEARCH_LANGUAGE_PREFERENCE);
downloadPathPreference =
(EditTextPreference) findPreference(DOWNLOAD_PATH_PREFERENCE);
downloadPathAudioPreference =
(EditTextPreference) findPreference(DOWNLOAD_PATH_AUDIO_PREFERENCE);
useTorCheckBox = (CheckBoxPreference) findPreference(USE_TOR_KEY);
prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Activity a = getActivity();
updateSummary();
if (defaultPreferences.getBoolean(USE_TOR_KEY, false)) {
if (OrbotHelper.isOrbotInstalled(a)) {
App.configureTor(true);
OrbotHelper.requestStartTor(a);
} else {
Intent intent = OrbotHelper.getOrbotInstallIntent(a);
a.startActivityForResult(intent, REQUEST_INSTALL_ORBOT);
}
} else {
App.configureTor(false);
}
}
};
defaultPreferences.registerOnSharedPreferenceChangeListener(prefListener);
updateSummary();
}
// This is used to show the status of some preference in the description
private void updateSummary() {
defaultResolutionPreference.setSummary(
defaultPreferences.getString(DEFAULT_RESOLUTION_PREFERENCE,
getString(R.string.default_resolution_value)));
defaultAudioFormatPreference.setSummary(
defaultPreferences.getString(DEFAULT_AUDIO_FORMAT_PREFERENCE,
getString(R.string.default_audio_format_value)));
searchLanguagePreference.setSummary(
defaultPreferences.getString(SEARCH_LANGUAGE_PREFERENCE,
getString(R.string.default_language_value)));
downloadPathPreference.setSummary(
defaultPreferences.getString(DOWNLOAD_PATH_PREFERENCE,
getString(R.string.download_path_summary)));
downloadPathAudioPreference.setSummary(
defaultPreferences.getString(DOWNLOAD_PATH_AUDIO_PREFERENCE,
getString(R.string.download_path_audio_summary)));
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// try to start tor regardless of resultCode since clicking back after
// installing the app does not necessarily return RESULT_OK
App.configureTor(requestCode == REQUEST_INSTALL_ORBOT
&& OrbotHelper.requestStartTor(this));
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
private ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
@NonNull
@Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
@Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
@Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home) {
finish();
}
return true;
}
public static void initSettings(Context context) {
NewPipeSettings.initSettings(context);
}
}

View File

@@ -0,0 +1,28 @@
package org.schabi.newpipe;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
public class ThemableActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (PreferenceManager.getDefaultSharedPreferences(this)
.getString("theme", getResources().getString(R.string.light_theme_title)).
equals(getResources().getString(R.string.dark_theme_title))) {
setTheme(R.style.DarkTheme);
}
}
@Override
protected void onResume() {
super.onResume();
if (PreferenceManager.getDefaultSharedPreferences(this)
.getString("theme", getResources().getString(R.string.light_theme_title)).
equals(getResources().getString(R.string.dark_theme_title))) {
setTheme(R.style.DarkTheme);
}
}
}

View File

@@ -1,94 +0,0 @@
package org.schabi.newpipe;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.schabi.newpipe.extractor.VideoPreviewInfo;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
/**
* Created by Christian Schabesberger on 24.10.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* VideoInfoItemViewCreator.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
class VideoInfoItemViewCreator {
private final LayoutInflater inflater;
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder().cacheInMemory(true).build();
public VideoInfoItemViewCreator(LayoutInflater inflater) {
this.inflater = inflater;
}
public View getViewFromVideoInfoItem(View convertView, ViewGroup parent, VideoPreviewInfo info, Context context) {
ViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.video_item, parent, false);
holder = new ViewHolder();
holder.itemThumbnailView = (ImageView) convertView.findViewById(R.id.itemThumbnailView);
holder.itemVideoTitleView = (TextView) convertView.findViewById(R.id.itemVideoTitleView);
holder.itemUploaderView = (TextView) convertView.findViewById(R.id.itemUploaderView);
holder.itemDurationView = (TextView) convertView.findViewById(R.id.itemDurationView);
holder.itemUploadDateView = (TextView) convertView.findViewById(R.id.itemUploadDateView);
holder.itemViewCountView = (TextView) convertView.findViewById(R.id.itemViewCountView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(info.thumbnail == null) {
holder.itemThumbnailView.setImageResource(R.drawable.dummy_thumbnail);
} else {
holder.itemThumbnailView.setImageBitmap(info.thumbnail);
}
holder.itemVideoTitleView.setText(info.title);
holder.itemUploaderView.setText(info.uploader);
holder.itemDurationView.setText(info.duration);
holder.itemViewCountView.setText(shortViewCount(info.view_count));
if(!info.upload_date.isEmpty()) {
holder.itemUploadDateView.setText(info.upload_date+"");
}
imageLoader.displayImage(info.thumbnail_url, holder.itemThumbnailView, displayImageOptions);
return convertView;
}
private class ViewHolder {
public ImageView itemThumbnailView;
public TextView itemVideoTitleView, itemUploaderView, itemDurationView, itemUploadDateView, itemViewCountView;
}
private String shortViewCount(Long view_count){
if(view_count >= 1000000000){
return Long.toString(view_count/1000000000)+"B views";
}else if(view_count>=1000000){
return Long.toString(view_count/1000000)+"M views";
}else if(view_count>=1000){
return Long.toString(view_count/1000)+"K views";
}else {
return Long.toString(view_count)+" views";
}
}
}

View File

@@ -1,157 +0,0 @@
package org.schabi.newpipe;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.schabi.newpipe.extractor.ServiceList;
import org.schabi.newpipe.extractor.StreamingService;
/**
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* VideoItemDetailActivity.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class VideoItemDetailActivity extends AppCompatActivity {
private static final String TAG = VideoItemDetailActivity.class.toString();
private VideoItemDetailFragment fragment;
private String videoUrl;
private int currentStreamingService = -1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videoitem_detail);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Show the Up button in the action bar.
try {
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} catch(Exception e) {
Log.d(TAG, "Could not get SupportActionBar");
e.printStackTrace();
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
Bundle arguments = new Bundle();
if (savedInstanceState == null) {
// this means the video was called though another app
if (getIntent().getData() != null) {
videoUrl = getIntent().getData().toString();
StreamingService[] serviceList = ServiceList.getServices();
//StreamExtractor videoExtractor = null;
for (int i = 0; i < serviceList.length; i++) {
if (serviceList[i].getUrlIdHandler().acceptUrl(videoUrl)) {
arguments.putInt(VideoItemDetailFragment.STREAMING_SERVICE, i);
currentStreamingService = i;
//videoExtractor = ServiceList.getService(i).getExtractorInstance();
break;
}
}
if(currentStreamingService == -1) {
Toast.makeText(this, R.string.url_not_supported_toast, Toast.LENGTH_LONG)
.show();
}
//arguments.putString(VideoItemDetailFragment.VIDEO_URL,
// videoExtractor.getVideoUrl(videoExtractor.getVideoId(videoUrl)));//cleans URL
arguments.putString(VideoItemDetailFragment.VIDEO_URL, videoUrl);
arguments.putBoolean(VideoItemDetailFragment.AUTO_PLAY,
PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean(getString(R.string.autoplay_through_intent_key), false));
} else {
videoUrl = getIntent().getStringExtra(VideoItemDetailFragment.VIDEO_URL);
currentStreamingService = getIntent().getIntExtra(VideoItemDetailFragment.STREAMING_SERVICE, -1);
arguments.putString(VideoItemDetailFragment.VIDEO_URL, videoUrl);
arguments.putInt(VideoItemDetailFragment.STREAMING_SERVICE, currentStreamingService);
arguments.putBoolean(VideoItemDetailFragment.AUTO_PLAY, false);
}
} else {
videoUrl = savedInstanceState.getString(VideoItemDetailFragment.VIDEO_URL);
currentStreamingService = savedInstanceState.getInt(VideoItemDetailFragment.STREAMING_SERVICE);
arguments = savedInstanceState;
}
// Create the detail fragment and add it to the activity
// using a fragment transaction.
fragment = new VideoItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.videoitem_detail_container, fragment)
.commit();
}
@Override
public void onResume() {
super.onResume();
App.checkStartTor(this);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(VideoItemDetailFragment.VIDEO_URL, videoUrl);
outState.putInt(VideoItemDetailFragment.STREAMING_SERVICE, currentStreamingService);
outState.putBoolean(VideoItemDetailFragment.AUTO_PLAY, false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
Intent intent = new Intent(this, VideoItemListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, intent);
return true;
} else {
return fragment.onOptionsItemSelected(item) ||
super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
fragment.onCreateOptionsMenu(menu, getMenuInflater());
return true;
}
}

View File

@@ -1,852 +0,0 @@
package org.schabi.newpipe;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.IOException;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
import java.util.Vector;
import org.schabi.newpipe.extractor.MediaFormat;
import org.schabi.newpipe.extractor.ParsingException;
import org.schabi.newpipe.extractor.ServiceList;
import org.schabi.newpipe.extractor.StreamExtractor;
import org.schabi.newpipe.extractor.VideoPreviewInfo;
import org.schabi.newpipe.extractor.StreamingService;
import org.schabi.newpipe.extractor.VideoInfo;
import org.schabi.newpipe.extractor.services.youtube.YoutubeStreamExtractor;
/**
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* VideoItemDetailFragment.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class VideoItemDetailFragment extends Fragment {
private static final String TAG = VideoItemDetailFragment.class.toString();
private static final String KORE_PACKET = "org.xbmc.kore";
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String VIDEO_URL = "video_url";
public static final String STREAMING_SERVICE = "streaming_service";
public static final String AUTO_PLAY = "auto_play";
private AppCompatActivity activity;
private ActionBarHandler actionBarHandler;
private ProgressBar progressBar;
private int streamingServiceId = -1;
private boolean autoPlayEnabled = false;
private boolean showNextVideoItem = false;
private Bitmap videoThumbnail;
private View thumbnailWindowLayout;
//this only remains due to downwards compatibility
private FloatingActionButton playVideoButton;
private final Point initialThumbnailPos = new Point(0, 0);
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions displayImageOptions =
new DisplayImageOptions.Builder().cacheInMemory(true).build();
public interface OnInvokeCreateOptionsMenuListener {
void createOptionsMenu();
}
private OnInvokeCreateOptionsMenuListener onInvokeCreateOptionsMenuListener = null;
private class VideoExtractorRunnable implements Runnable {
private final Handler h = new Handler();
private StreamExtractor streamExtractor;
private final StreamingService service;
private final String videoUrl;
public VideoExtractorRunnable(String videoUrl, StreamingService service) {
this.service = service;
this.videoUrl = videoUrl;
}
@Override
public void run() {
try {
streamExtractor = service.getExtractorInstance(videoUrl, new Downloader());
VideoInfo videoInfo = VideoInfo.getVideoInfo(streamExtractor, new Downloader());
h.post(new VideoResultReturnedRunnable(videoInfo));
} catch (IOException e) {
postNewErrorToast(h, R.string.network_error);
e.printStackTrace();
}
// custom service related exceptions
catch (YoutubeStreamExtractor.DecryptException de) {
postNewErrorToast(h, R.string.youtube_signature_decryption_error);
de.printStackTrace();
} catch (YoutubeStreamExtractor.GemaException ge) {
h.post(new Runnable() {
@Override
public void run() {
onErrorBlockedByGema();
}
});
}
// ----------------------------------------
catch(StreamExtractor.ContentNotAvailableException e) {
h.post(new Runnable() {
@Override
public void run() {
onNotSpecifiedContentError();
}
});
e.printStackTrace();
} catch (ParsingException e) {
postNewErrorToast(h, e.getMessage());
e.printStackTrace();
} catch(Exception e) {
postNewErrorToast(h, R.string.general_error);
e.printStackTrace();
}
}
}
private class VideoResultReturnedRunnable implements Runnable {
private final VideoInfo videoInfo;
public VideoResultReturnedRunnable(VideoInfo videoInfo) {
this.videoInfo = videoInfo;
}
@Override
public void run() {
//todo: fix expired thread error:
// If the thread calling this runnable is expired, the following function will crash.
updateInfo(videoInfo);
}
}
private class ThumbnailLoadingListener implements ImageLoadingListener {
@Override
public void onLoadingStarted(String imageUri, View view) {}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
Toast.makeText(VideoItemDetailFragment.this.getActivity(),
R.string.could_not_load_thumbnails, Toast.LENGTH_LONG).show();
failReason.getCause().printStackTrace();
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {}
@Override
public void onLoadingCancelled(String imageUri, View view) {}
}
private void updateInfo(final VideoInfo info) {
try {
Context c = getContext();
VideoInfoItemViewCreator videoItemViewCreator =
new VideoInfoItemViewCreator(LayoutInflater.from(getActivity()));
RelativeLayout textContentLayout =
(RelativeLayout) activity.findViewById(R.id.detailTextContentLayout);
final TextView videoTitleView =
(TextView) activity.findViewById(R.id.detailVideoTitleView);
TextView uploaderView = (TextView) activity.findViewById(R.id.detailUploaderView);
TextView viewCountView = (TextView) activity.findViewById(R.id.detailViewCountView);
TextView thumbsUpView = (TextView) activity.findViewById(R.id.detailThumbsUpCountView);
TextView thumbsDownView =
(TextView) activity.findViewById(R.id.detailThumbsDownCountView);
TextView uploadDateView = (TextView) activity.findViewById(R.id.detailUploadDateView);
TextView descriptionView = (TextView) activity.findViewById(R.id.detailDescriptionView);
FrameLayout nextVideoFrame =
(FrameLayout) activity.findViewById(R.id.detailNextVideoFrame);
RelativeLayout nextVideoRootFrame =
(RelativeLayout) activity.findViewById(R.id.detailNextVideoRootLayout);
Button nextVideoButton = (Button) activity.findViewById(R.id.detailNextVideoButton);
TextView similarTitle = (TextView) activity.findViewById(R.id.detailSimilarTitle);
Button backgroundButton = (Button)
activity.findViewById(R.id.detailVideoThumbnailWindowBackgroundButton);
View topView = activity.findViewById(R.id.detailTopView);
View nextVideoView = null;
if(info.next_video != null) {
nextVideoView = videoItemViewCreator
.getViewFromVideoInfoItem(null, nextVideoFrame, info.next_video, getContext());
} else {
activity.findViewById(R.id.detailNextVidButtonAndContentLayout).setVisibility(View.GONE);
activity.findViewById(R.id.detailNextVideoTitle).setVisibility(View.GONE);
activity.findViewById(R.id.detailNextVideoButton).setVisibility(View.GONE);
}
progressBar.setVisibility(View.GONE);
if(nextVideoView != null) {
nextVideoFrame.addView(nextVideoView);
}
initThumbnailViews(info, nextVideoFrame);
textContentLayout.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT < 18) {
playVideoButton.setVisibility(View.VISIBLE);
} else {
ImageView playArrowView = (ImageView) activity.findViewById(R.id.playArrowView);
playArrowView.setVisibility(View.VISIBLE);
}
if (!showNextVideoItem) {
nextVideoRootFrame.setVisibility(View.GONE);
similarTitle.setVisibility(View.GONE);
}
videoTitleView.setText(info.title);
topView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
ImageView arrow = (ImageView) activity.findViewById(R.id.toggleDescriptionView);
View extra = activity.findViewById(R.id.detailExtraView);
if (extra.getVisibility() == View.VISIBLE) {
extra.setVisibility(View.GONE);
arrow.setImageResource(R.drawable.arrow_down);
} else {
extra.setVisibility(View.VISIBLE);
arrow.setImageResource(R.drawable.arrow_up);
}
}
return true;
}
});
// Since newpipe is designed to work even if certain information is not available,
// the UI has to react on missing information.
videoTitleView.setText(info.title);
if(!info.uploader.isEmpty()) {
uploaderView.setText(info.uploader);
} else {
activity.findViewById(R.id.detailUploaderWrapView).setVisibility(View.GONE);
}
if(info.view_count >= 0) {
viewCountView.setText(Localization.localizeViewCount(info.view_count, c));
} else {
viewCountView.setVisibility(View.GONE);
}
if(info.dislike_count >= 0) {
thumbsDownView.setText(Localization.localizeNumber(info.dislike_count, c));
} else {
thumbsDownView.setVisibility(View.INVISIBLE);
activity.findViewById(R.id.detailThumbsDownImgView).setVisibility(View.GONE);
}
if(info.like_count >= 0) {
thumbsUpView.setText(Localization.localizeNumber(info.like_count, c));
} else {
thumbsUpView.setVisibility(View.GONE);
activity.findViewById(R.id.detailThumbsUpImgView).setVisibility(View.GONE);
thumbsDownView.setVisibility(View.GONE);
activity.findViewById(R.id.detailThumbsDownImgView).setVisibility(View.GONE);
}
if(!info.upload_date.isEmpty()) {
uploadDateView.setText(Localization.localizeDate(info.upload_date, c));
} else {
uploadDateView.setVisibility(View.GONE);
}
if(!info.description.isEmpty()) {
descriptionView.setText(Html.fromHtml(info.description));
} else {
descriptionView.setVisibility(View.GONE);
}
descriptionView.setMovementMethod(LinkMovementMethod.getInstance());
// parse streams
Vector<VideoInfo.VideoStream> streamsToUse = new Vector<>();
for (VideoInfo.VideoStream i : info.video_streams) {
if (useStream(i, streamsToUse)) {
streamsToUse.add(i);
}
}
nextVideoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent detailIntent =
new Intent(getActivity(), VideoItemDetailActivity.class);
/*detailIntent.putExtra(
VideoItemDetailFragment.ARG_ITEM_ID, currentVideoInfo.nextVideo.id); */
detailIntent.putExtra(
VideoItemDetailFragment.VIDEO_URL, info.next_video.webpage_url);
detailIntent.putExtra(VideoItemDetailFragment.STREAMING_SERVICE, streamingServiceId);
startActivity(detailIntent);
}
});
textContentLayout.setVisibility(View.VISIBLE);
if(info.related_videos != null && !info.related_videos.isEmpty()) {
initSimilarVideos(info, videoItemViewCreator);
} else {
activity.findViewById(R.id.detailSimilarTitle).setVisibility(View.GONE);
activity.findViewById(R.id.similarVideosView).setVisibility(View.GONE);
}
setupActionBarHandler(info);
if(autoPlayEnabled) {
playVideo(info);
}
if (android.os.Build.VERSION.SDK_INT < 18) {
playVideoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playVideo(info);
}
});
}
backgroundButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playVideo(info);
}
});
} catch (java.lang.NullPointerException e) {
Log.w(TAG, "updateInfo(): Fragment closed before thread ended work... or else");
e.printStackTrace();
}
}
private void initThumbnailViews(VideoInfo info, View nextVideoFrame) {
ImageView videoThumbnailView = (ImageView) activity.findViewById(R.id.detailThumbnailView);
ImageView uploaderThumb
= (ImageView) activity.findViewById(R.id.detailUploaderThumbnailView);
ImageView nextVideoThumb =
(ImageView) nextVideoFrame.findViewById(R.id.itemThumbnailView);
if(info.thumbnail_url != null && !info.thumbnail_url.isEmpty()) {
imageLoader.displayImage(info.thumbnail_url, videoThumbnailView,
displayImageOptions, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
Toast.makeText(VideoItemDetailFragment.this.getActivity(),
R.string.could_not_load_thumbnails, Toast.LENGTH_LONG).show();
failReason.getCause().printStackTrace();
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
videoThumbnail = loadedImage;
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
});
} else {
videoThumbnailView.setImageResource(R.drawable.dummy_thumbnail_dark);
}
if(info.uploader_thumbnail_url != null && !info.uploader_thumbnail_url.isEmpty()) {
imageLoader.displayImage(info.uploader_thumbnail_url,
uploaderThumb, displayImageOptions, new ThumbnailLoadingListener());
}
if(info.thumbnail_url != null && !info.thumbnail_url.isEmpty()) {
imageLoader.displayImage(info.next_video.thumbnail_url,
nextVideoThumb, displayImageOptions, new ThumbnailLoadingListener());
}
}
private void setupActionBarHandler(final VideoInfo info) {
actionBarHandler.setupStreamList(info.video_streams);
actionBarHandler.setOnShareListener(new ActionBarHandler.OnActionListener() {
@Override
public void onActionSelected(int selectedStreamId) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, info.webpage_url);
intent.setType("text/plain");
activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.share_dialog_title)));
}
});
actionBarHandler.setOnOpenInBrowserListener(new ActionBarHandler.OnActionListener() {
@Override
public void onActionSelected(int selectedStreamId) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(info.webpage_url));
activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.choose_browser)));
}
});
actionBarHandler.setOnPlayWithKodiListener(new ActionBarHandler.OnActionListener() {
@Override
public void onActionSelected(int selectedStreamId) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setPackage(KORE_PACKET);
intent.setData(Uri.parse(info.webpage_url.replace("https", "http")));
activity.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(R.string.kore_not_found)
.setPositiveButton(R.string.install, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(activity.getString(R.string.fdroid_kore_url)));
activity.startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
}
});
actionBarHandler.setOnDownloadListener(new ActionBarHandler.OnActionListener() {
@Override
public void onActionSelected(int selectedStreamId) {
try {
Bundle args = new Bundle();
// Sometimes it may be that some information is not available due to changes fo the
// website which was crawled. Then the ui has to understand this and act right.
if (info.audio_streams != null) {
VideoInfo.AudioStream audioStream =
info.audio_streams.get(getPreferredAudioStreamId(info));
String audioSuffix = "." + MediaFormat.getSuffixById(audioStream.format);
args.putString(DownloadDialog.AUDIO_URL, audioStream.url);
args.putString(DownloadDialog.FILE_SUFFIX_AUDIO, audioSuffix);
}
if (info.video_streams != null) {
VideoInfo.VideoStream selectedStreamItem = info.video_streams.get(selectedStreamId);
String videoSuffix = "." + MediaFormat.getSuffixById(selectedStreamItem.format);
args.putString(DownloadDialog.FILE_SUFFIX_VIDEO, videoSuffix);
args.putString(DownloadDialog.VIDEO_URL, selectedStreamItem.url);
}
args.putString(DownloadDialog.TITLE, info.title);
DownloadDialog downloadDialog = new DownloadDialog();
downloadDialog.setArguments(args);
downloadDialog.show(activity.getSupportFragmentManager(), "downloadDialog");
} catch (Exception e) {
Toast.makeText(VideoItemDetailFragment.this.getActivity(),
R.string.could_not_setup_download_menu, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
if(info.audio_streams == null) {
actionBarHandler.showAudioAction(false);
} else {
actionBarHandler.setOnPlayAudioListener(new ActionBarHandler.OnActionListener() {
@Override
public void onActionSelected(int selectedStreamId) {
boolean useExternalAudioPlayer = PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(activity.getString(R.string.use_external_audio_player_key), false);
Intent intent;
VideoInfo.AudioStream audioStream =
info.audio_streams.get(getPreferredAudioStreamId(info));
if (!useExternalAudioPlayer && android.os.Build.VERSION.SDK_INT >= 18) {
//internal music player: explicit intent
if (!BackgroundPlayer.isRunning && videoThumbnail != null) {
ActivityCommunicator.getCommunicator()
.backgroundPlayerThumbnail = videoThumbnail;
intent = new Intent(activity, BackgroundPlayer.class);
intent.setAction(Intent.ACTION_VIEW);
Log.i(TAG, "audioStream is null:" + (audioStream == null));
Log.i(TAG, "audioStream.url is null:" + (audioStream.url == null));
intent.setDataAndType(Uri.parse(audioStream.url),
MediaFormat.getMimeById(audioStream.format));
intent.putExtra(BackgroundPlayer.TITLE, info.title);
intent.putExtra(BackgroundPlayer.WEB_URL, info.webpage_url);
intent.putExtra(BackgroundPlayer.SERVICE_ID, streamingServiceId);
intent.putExtra(BackgroundPlayer.CHANNEL_NAME, info.uploader);
activity.startService(intent);
}
} else {
intent = new Intent();
try {
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(audioStream.url),
MediaFormat.getMimeById(audioStream.format));
intent.putExtra(Intent.EXTRA_TITLE, info.title);
intent.putExtra("title", info.title);
// HERE !!!
activity.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(R.string.no_player_found)
.setPositiveButton(R.string.install, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(activity.getString(R.string.fdroid_vlc_url)));
activity.startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, "You unlocked a secret unicorn.");
}
});
builder.create().show();
Log.e(TAG, "Either no Streaming player for audio was installed, or something important crashed:");
e.printStackTrace();
}
}
}
});
}
}
private int getPreferredAudioStreamId(final VideoInfo info) {
String preferredFormatString = PreferenceManager.getDefaultSharedPreferences(getActivity())
.getString(activity.getString(R.string.default_audio_format_key), "webm");
int preferredFormat = MediaFormat.WEBMA.id;
switch(preferredFormatString) {
case "webm":
preferredFormat = MediaFormat.WEBMA.id;
break;
case "m4a":
preferredFormat = MediaFormat.M4A.id;
break;
default:
break;
}
for(int i = 0; i < info.audio_streams.size(); i++) {
if(info.audio_streams.get(i).format == preferredFormat) {
return i;
}
}
//todo: make this a proper error
Log.e(TAG, "FAILED to set audioStream value!");
return 0;
}
private void initSimilarVideos(final VideoInfo info, VideoInfoItemViewCreator videoItemViewCreator) {
LinearLayout similarLayout = (LinearLayout) activity.findViewById(R.id.similarVideosView);
ArrayList<VideoPreviewInfo> similar = new ArrayList<>(info.related_videos);
for (final VideoPreviewInfo item : similar) {
View similarView = videoItemViewCreator
.getViewFromVideoInfoItem(null, similarLayout, item, getContext());
similarView.setClickable(true);
similarView.setFocusable(true);
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = activity.obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
similarView.setBackgroundResource(backgroundResource);
typedArray.recycle();
similarView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Intent detailIntent = new Intent(activity, VideoItemDetailActivity.class);
detailIntent.putExtra(VideoItemDetailFragment.VIDEO_URL, item.webpage_url);
detailIntent.putExtra(
VideoItemDetailFragment.STREAMING_SERVICE, streamingServiceId);
startActivity(detailIntent);
return true;
}
return false;
}
});
similarLayout.addView(similarView);
ImageView rthumb = (ImageView)similarView.findViewById(R.id.itemThumbnailView);
imageLoader.displayImage(item.thumbnail_url, rthumb,
displayImageOptions, new ThumbnailLoadingListener());
}
}
private void onErrorBlockedByGema() {
Button backgroundButton = (Button)
activity.findViewById(R.id.detailVideoThumbnailWindowBackgroundButton);
ImageView thumbnailView = (ImageView) activity.findViewById(R.id.detailThumbnailView);
progressBar.setVisibility(View.GONE);
thumbnailView.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.drawable.gruese_die_gema));
backgroundButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(activity.getString(R.string.c3s_url)));
activity.startActivity(intent);
}
});
Toast.makeText(VideoItemDetailFragment.this.getActivity(),
R.string.blocked_by_gema, Toast.LENGTH_LONG).show();
}
private void onNotSpecifiedContentError() {
ImageView thumbnailView = (ImageView) activity.findViewById(R.id.detailThumbnailView);
progressBar.setVisibility(View.GONE);
thumbnailView.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.drawable.not_available_monkey));
Toast.makeText(activity, R.string.content_not_available, Toast.LENGTH_LONG)
.show();
}
private boolean useStream(VideoInfo.VideoStream stream, Vector<VideoInfo.VideoStream> streams) {
for(VideoInfo.VideoStream i : streams) {
if(i.resolution.equals(stream.resolution)) {
return false;
}
}
return true;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = (AppCompatActivity) getActivity();
showNextVideoItem = PreferenceManager.getDefaultSharedPreferences(getActivity())
.getBoolean(activity.getString(R.string.show_next_video_key), true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_videoitem_detail, container, false);
progressBar = (ProgressBar) rootView.findViewById(R.id.detailProgressBar);
actionBarHandler = new ActionBarHandler(activity);
actionBarHandler.setupNavMenu(activity);
if(onInvokeCreateOptionsMenuListener != null) {
onInvokeCreateOptionsMenuListener.createOptionsMenu();
}
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceBundle) {
super.onActivityCreated(savedInstanceBundle);
Activity a = getActivity();
if (android.os.Build.VERSION.SDK_INT < 18) {
playVideoButton = (FloatingActionButton) a.findViewById(R.id.playVideoButton);
}
thumbnailWindowLayout = a.findViewById(R.id.detailVideoThumbnailWindowLayout);
Button backgroundButton = (Button)
a.findViewById(R.id.detailVideoThumbnailWindowBackgroundButton);
// Sometimes when this fragment is not visible it still gets initiated
// then we must not try to access objects of this fragment.
// Otherwise the applications would crash.
if(backgroundButton != null) {
try {
streamingServiceId = getArguments().getInt(STREAMING_SERVICE);
StreamingService streamingService = ServiceList.getService(streamingServiceId);
Thread videoExtractorThread = new Thread(new VideoExtractorRunnable(
getArguments().getString(VIDEO_URL), streamingService));
autoPlayEnabled = getArguments().getBoolean(AUTO_PLAY);
videoExtractorThread.start();
} catch (Exception e) {
e.printStackTrace();
}
if(Build.VERSION.SDK_INT >= 18) {
ImageView thumbnailView = (ImageView) activity.findViewById(R.id.detailThumbnailView);
thumbnailView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
// This is used to synchronize the thumbnailWindowButton and the playVideoButton
// inside the ScrollView with the actual size of the thumbnail.
//todo: onLayoutChage sometimes not triggered
// background buttons area seem to overlap the thumbnail view
// So although you just clicked slightly beneath the thumbnail the action still
// gets triggered.
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
RelativeLayout.LayoutParams newWindowLayoutParams =
(RelativeLayout.LayoutParams) thumbnailWindowLayout.getLayoutParams();
newWindowLayoutParams.height = bottom - top;
thumbnailWindowLayout.setLayoutParams(newWindowLayoutParams);
//noinspection SuspiciousNameCombination
initialThumbnailPos.set(top, left);
}
});
}
}
}
public void playVideo(final VideoInfo info) {
// ----------- THE MAGIC MOMENT ---------------
VideoInfo.VideoStream selectedVideoStream =
info.video_streams.get(actionBarHandler.getSelectedVideoStream());
if (PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(activity.getString(R.string.use_external_video_player_key), false)) {
// External Player
Intent intent = new Intent();
try {
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(selectedVideoStream.url),
MediaFormat.getMimeById(selectedVideoStream.format));
intent.putExtra(Intent.EXTRA_TITLE, info.title);
intent.putExtra("title", info.title);
activity.startActivity(intent); // HERE !!!
} catch (Exception e) {
e.printStackTrace();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(R.string.no_player_found)
.setPositiveButton(R.string.install, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(activity.getString(R.string.fdroid_vlc_url)));
activity.startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
} else {
// Internal Player
Intent intent = new Intent(activity, PlayVideoActivity.class);
intent.putExtra(PlayVideoActivity.VIDEO_TITLE, info.title);
intent.putExtra(PlayVideoActivity.STREAM_URL, selectedVideoStream.url);
intent.putExtra(PlayVideoActivity.VIDEO_URL, info.webpage_url);
intent.putExtra(PlayVideoActivity.START_POSITION, info.start_position);
activity.startActivity(intent); //also HERE !!!
}
// --------------------------------------------
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
actionBarHandler.setupMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return actionBarHandler.onItemSelected(item);
}
public void setOnInvokeCreateOptionsMenuListener(OnInvokeCreateOptionsMenuListener listener) {
this.onInvokeCreateOptionsMenuListener = listener;
}
private void postNewErrorToast(Handler h, final int stringResource) {
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(VideoItemDetailFragment.this.getActivity(),
stringResource, Toast.LENGTH_LONG).show();
}
});
}
private void postNewErrorToast(Handler h, final String message) {
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(VideoItemDetailFragment.this.getActivity(),
message, Toast.LENGTH_LONG).show();
}
});
}
}

View File

@@ -1,284 +0,0 @@
package org.schabi.newpipe;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import java.util.ArrayList;
import org.schabi.newpipe.extractor.VideoPreviewInfo;
import org.schabi.newpipe.extractor.ServiceList;
/**
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* VideoItemListActivity.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class VideoItemListActivity extends AppCompatActivity
implements VideoItemListFragment.Callbacks {
private static final String TAG = VideoItemListFragment.class.toString();
// arguments to give to this activity
public static final String VIDEO_INFO_ITEMS = "video_info_items";
// savedInstanceBundle arguments
private static final String QUERY = "query";
private static final String STREAMING_SERVICE = "streaming_service";
// activity modes
private static final int SEARCH_MODE = 0;
private static final int PRESENT_VIDEOS_MODE = 1;
private int mode = SEARCH_MODE;
private int currentStreamingServiceId = -1;
private String searchQuery = "";
private VideoItemListFragment listFragment;
private VideoItemDetailFragment videoFragment = null;
private Menu menu = null;
private class SearchVideoQueryListener implements SearchView.OnQueryTextListener {
@Override
public boolean onQueryTextSubmit(String query) {
try {
searchQuery = query;
listFragment.search(query);
// hide virtual keyboard
InputMethodManager inputManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
try {
//noinspection ConstantConditions
inputManager.hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch(NullPointerException e) {
Log.e(TAG, "Could not get widget with focus");
e.printStackTrace();
}
// clear focus
// 1. to not open up the keyboard after switching back to this
// 2. It's a workaround to a seeming bug by the Android OS it self, causing
// onQueryTextSubmit to trigger twice when focus is not cleared.
// See: http://stackoverflow.com/questions/17874951/searchview-onquerytextsubmit-runs-twice-while-i-pressed-once
getCurrentFocus().clearFocus();
} catch(Exception e) {
e.printStackTrace();
}
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return true;
}
}
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videoitem_list);
//------ todo: remove this line when multiservice support is implemented ------
currentStreamingServiceId = ServiceList.getIdOfService("Youtube");
//-----------------------------------------------------------------------------
//to solve issue 38
listFragment = (VideoItemListFragment) getSupportFragmentManager()
.findFragmentById(R.id.videoitem_list);
listFragment.setStreamingService(ServiceList.getService(currentStreamingServiceId));
Bundle arguments = getIntent().getExtras();
if(arguments != null) {
//Parcelable[] p = arguments.getParcelableArray(VIDEO_INFO_ITEMS);
ArrayList<VideoPreviewInfo> p = arguments.getParcelableArrayList(VIDEO_INFO_ITEMS);
if(p != null) {
mode = PRESENT_VIDEOS_MODE;
try {
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} catch (NullPointerException e) {
Log.e(TAG, "Could not get SupportActionBar");
e.printStackTrace();
}
listFragment.present(p);
}
}
if(savedInstanceState != null
&& mode != PRESENT_VIDEOS_MODE) {
searchQuery = savedInstanceState.getString(QUERY);
currentStreamingServiceId = savedInstanceState.getInt(STREAMING_SERVICE);
if(!searchQuery.isEmpty()) {
listFragment.search(searchQuery);
}
}
if (findViewById(R.id.videoitem_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((VideoItemListFragment) getSupportFragmentManager()
.findFragmentById(R.id.videoitem_list))
.setActivateOnItemClick(true);
SearchView searchView = (SearchView)findViewById(R.id.searchViewTablet);
if(mode != PRESENT_VIDEOS_MODE) {
// Somehow the seticonifiedbydefault property set by the layout xml is not working on
// the support version on SearchView, so it needs to be set programmatically.
searchView.setIconifiedByDefault(false);
searchView.setIconified(false);
searchView.setOnQueryTextListener(new SearchVideoQueryListener());
} else {
searchView.setVisibility(View.GONE);
}
}
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
}
@Override
public void onResume() {
super.onResume();
App.checkStartTor(this);
}
/**
* Callback method from {@link VideoItemListFragment.Callbacks}
* indicating that the item with the given ID was selected.
*/
@Override
public void onItemSelected(String id) {
VideoListAdapter listAdapter = (VideoListAdapter) ((VideoItemListFragment)
getSupportFragmentManager()
.findFragmentById(R.id.videoitem_list))
.getListAdapter();
String webpage_url = listAdapter.getVideoList().get((int) Long.parseLong(id)).webpage_url;
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
//arguments.putString(VideoItemDetailFragment.ARG_ITEM_ID, id);
arguments.putString(VideoItemDetailFragment.VIDEO_URL, webpage_url);
arguments.putInt(VideoItemDetailFragment.STREAMING_SERVICE, currentStreamingServiceId);
videoFragment = new VideoItemDetailFragment();
videoFragment.setArguments(arguments);
videoFragment.setOnInvokeCreateOptionsMenuListener(new VideoItemDetailFragment.OnInvokeCreateOptionsMenuListener() {
@Override
public void createOptionsMenu() {
menu.clear();
onCreateOptionsMenu(menu);
}
});
getSupportFragmentManager().beginTransaction()
.replace(R.id.videoitem_detail_container, videoFragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, VideoItemDetailActivity.class);
//detailIntent.putExtra(VideoItemDetailFragment.ARG_ITEM_ID, id);
detailIntent.putExtra(VideoItemDetailFragment.VIDEO_URL, webpage_url);
detailIntent.putExtra(VideoItemDetailFragment.STREAMING_SERVICE, currentStreamingServiceId);
startActivity(detailIntent);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.menu = menu;
MenuInflater inflater = getMenuInflater();
if(mode != PRESENT_VIDEOS_MODE &&
findViewById(R.id.videoitem_detail_container) == null) {
inflater.inflate(R.menu.videoitem_list, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setFocusable(false);
searchView.setOnQueryTextListener(
new SearchVideoQueryListener());
} else if (videoFragment != null){
videoFragment.onCreateOptionsMenu(menu, inflater);
} else {
inflater.inflate(R.menu.videoitem_two_pannel, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case android.R.id.home: {
Intent intent = new Intent(this, VideoItemListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, intent);
return true;
}
case R.id.action_settings: {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
default:
return videoFragment.onOptionsItemSelected(item) ||
super.onOptionsItemSelected(item);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/*
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
*/
outState.putString(QUERY, searchQuery);
outState.putInt(STREAMING_SERVICE, currentStreamingServiceId);
}
}

View File

@@ -1,386 +0,0 @@
package org.schabi.newpipe;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import org.schabi.newpipe.extractor.ExctractionException;
import org.schabi.newpipe.extractor.VideoPreviewInfo;
import org.schabi.newpipe.extractor.SearchEngine;
import org.schabi.newpipe.extractor.StreamingService;
/**
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* VideoItemListFragment.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class VideoItemListFragment extends ListFragment {
private static final String TAG = VideoItemListFragment.class.toString();
private StreamingService streamingService = null;
private VideoListAdapter videoListAdapter;
// activity modes
private static final int SEARCH_MODE = 0;
private static final int PRESENT_VIDEOS_MODE = 1;
private int mode = SEARCH_MODE;
private String query = "";
private int lastPage = 0;
private Thread searchThread = null;
private SearchRunnable searchRunnable = null;
// used to track down if results posted by threads ar still valid
private int currentRequestId = -1;
private ListView list;
private View footer;
// used to suppress request for loading a new page while another page is already loading.
private boolean loadingNextPage = true;
private class ResultRunnable implements Runnable {
private final SearchEngine.Result result;
private final int requestId;
public ResultRunnable(SearchEngine.Result result, int requestId) {
this.result = result;
this.requestId = requestId;
}
@Override
public void run() {
updateListOnResult(result, requestId);
if (android.os.Build.VERSION.SDK_INT >= 19) {
getListView().removeFooterView(footer);
}
}
}
private class SearchRunnable implements Runnable {
private final SearchEngine engine;
private final String query;
private final int page;
final Handler h = new Handler();
private volatile boolean runs = true;
private final int requestId;
public SearchRunnable(SearchEngine engine, String query, int page, int requestId) {
this.engine = engine;
this.query = query;
this.page = page;
this.requestId = requestId;
}
void terminate() {
runs = false;
}
@Override
public void run() {
try {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
String searchLanguageKey = getContext().getString(R.string.search_language_key);
String searchLanguage = sp.getString(searchLanguageKey,
getString(R.string.default_language_value));
SearchEngine.Result result = engine.search(query, page, searchLanguage,
new Downloader());
Log.i(TAG, "language code passed:\""+searchLanguage+"\"");
if(runs) {
h.post(new ResultRunnable(result, requestId));
}
} catch(IOException e) {
postNewErrorToast(h, R.string.network_error);
e.printStackTrace();
} catch(ExctractionException ce) {
postNewErrorToast(h, R.string.parsing_error);
ce.printStackTrace();
} catch(Exception e) {
postNewErrorToast(h, R.string.general_error);
e.printStackTrace();
}
}
}
/*
<<<
private class LoadThumbsRunnable implements Runnable {
private final Vector<String> thumbnailUrlList = new Vector<>();
private final Vector<Boolean> downloadedList;
final Handler h = new Handler();
private volatile boolean run = true;
private final int requestId;
public LoadThumbsRunnable(Vector<VideoPreviewInfo> videoList,
Vector<Boolean> downloadedList, int requestId) {
for(VideoPreviewInfo item : videoList) {
thumbnailUrlList.add(item.thumbnail_url);
}
this.downloadedList = downloadedList;
this.requestId = requestId;
}
public void terminate() {
run = false;
}
public boolean isRunning() {
return run;
}
@Override
public void run() {
for(int i = 0; i < thumbnailUrlList.size() && run; i++) {
if(!downloadedList.get(i)) {
Bitmap thumbnail;
try {
//todo: make bitmaps not bypass tor
thumbnail = BitmapFactory.decodeStream(
new URL(thumbnailUrlList.get(i)).openConnection().getInputStream());
h.post(new SetThumbnailRunnable(i, thumbnail, requestId));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
private class SetThumbnailRunnable implements Runnable {
private final int index;
private final Bitmap thumbnail;
private final int requestId;
public SetThumbnailRunnable(int index, Bitmap thumbnail, int requestId) {
this.index = index;
this.thumbnail = thumbnail;
this.requestId = requestId;
}
@Override
public void run() {
if(requestId == currentRequestId) {
videoListAdapter.updateDownloadedThumbnailList(index);
videoListAdapter.setThumbnail(index, thumbnail);
}
}
}
=======
>>>>>>> 6d1b4652fc98e5c2d5e19b0f98ba38a731137a70
*/
public void present(List<VideoPreviewInfo> videoList) {
mode = PRESENT_VIDEOS_MODE;
setListShown(true);
getListView().smoothScrollToPosition(0);
updateList(videoList);
}
public void search(String query) {
mode = SEARCH_MODE;
this.query = query;
this.lastPage = 1;
videoListAdapter.clearVideoList();
setListShown(false);
startSearch(query, lastPage);
//todo: Somehow this command is not working on older devices,
// although it was introduced with API level 8. Test this and find a solution.
getListView().smoothScrollToPosition(0);
}
private void nextPage() {
loadingNextPage = true;
lastPage++;
Log.d(TAG, getString(R.string.search_page) + Integer.toString(lastPage));
startSearch(query, lastPage);
}
private void startSearch(String query, int page) {
currentRequestId++;
terminateThreads();
searchRunnable = new SearchRunnable(streamingService.getSearchEngineInstance(),
query, page, currentRequestId);
searchThread = new Thread(searchRunnable);
searchThread.start();
}
public void setStreamingService(StreamingService streamingService) {
this.streamingService = streamingService;
}
private void updateListOnResult(SearchEngine.Result result, int requestId) {
if(requestId == currentRequestId) {
setListShown(true);
if (result.resultList.isEmpty()) {
Toast.makeText(getActivity(), result.errorMessage, Toast.LENGTH_LONG).show();
} else {
if (!result.suggestion.isEmpty()) {
Toast.makeText(getActivity(), getString(R.string.did_you_mean) + result.suggestion + " ?",
Toast.LENGTH_LONG).show();
}
updateList(result.resultList);
}
}
}
private void updateList(List<VideoPreviewInfo> list) {
try {
videoListAdapter.addVideoList(list);
terminateThreads();
} catch(java.lang.IllegalStateException e) {
Log.w(TAG, "Trying to set value while activity doesn't exist anymore.");
} catch(Exception e) {
e.printStackTrace();
} finally {
loadingNextPage = false;
}
}
private void terminateThreads() {
if(searchThread != null) {
searchRunnable.terminate();
// No need to join, since we don't really terminate the thread. We just demand
// it to post its result runnable into the gui main loop.
}
}
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
void onItemSelected(String id);
}
private Callbacks mCallbacks = null;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
list = getListView();
videoListAdapter = new VideoListAdapter(getActivity(), this);
footer = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.paginate_footer, null, false);
setListAdapter(videoListAdapter);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
long lastScrollDate = 0;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mode != PRESENT_VIDEOS_MODE
&& list.getChildAt(0) != null
&& list.getLastVisiblePosition() == list.getAdapter().getCount() - 1
&& list.getChildAt(list.getChildCount() - 1).getBottom() <= list.getHeight()) {
long time = System.currentTimeMillis();
if ((time - lastScrollDate) > 200
&& !loadingNextPage) {
lastScrollDate = time;
getListView().addFooterView(footer);
nextPage();
}
}
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Activities containing this fragment must implement its callbacks.
if (!(context instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) context;
}
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
setActivatedPosition(position);
mCallbacks.onItemSelected(Long.toString(id));
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(@SuppressWarnings("SameParameterValue") boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(activateOnItemClick
? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
private void postNewErrorToast(Handler h, final int stringResource) {
h.post(new Runnable() {
@Override
public void run() {
setListShown(true);
Toast.makeText(getActivity(), getString(R.string.network_error),
Toast.LENGTH_SHORT).show();
}
});
}
}

View File

@@ -1,91 +0,0 @@
package org.schabi.newpipe;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import org.schabi.newpipe.extractor.VideoPreviewInfo;
import java.util.List;
import java.util.Vector;
/**
* Created by Christian Schabesberger on 11.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* VideoListAdapter.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
class VideoListAdapter extends BaseAdapter {
private final Context context;
private final VideoInfoItemViewCreator viewCreator;
private Vector<VideoPreviewInfo> videoList = new Vector<>();
private final ListView listView;
public VideoListAdapter(Context context, VideoItemListFragment videoListFragment) {
viewCreator = new VideoInfoItemViewCreator(LayoutInflater.from(context));
this.listView = videoListFragment.getListView();
this.listView.setDivider(null);
this.listView.setDividerHeight(0);
this.context = context;
}
public void addVideoList(List<VideoPreviewInfo> videos) {
videoList.addAll(videos);
notifyDataSetChanged();
}
public void clearVideoList() {
videoList = new Vector<>();
notifyDataSetChanged();
}
public Vector<VideoPreviewInfo> getVideoList() {
return videoList;
}
@Override
public int getCount() {
return videoList.size();
}
@Override
public Object getItem(int position) {
return videoList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = viewCreator.getViewFromVideoInfoItem(convertView, parent, videoList.get(position), context);
if(listView.isItemChecked(position)) {
convertView.setBackgroundColor(ContextCompat.getColor(context,R.color.light_youtube_primary_color));
} else {
convertView.setBackgroundColor(0);
}
return convertView;
}
}

View File

@@ -0,0 +1,251 @@
package org.schabi.newpipe.download;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import org.schabi.newpipe.R;
import org.schabi.newpipe.report.ErrorActivity;
import org.schabi.newpipe.settings.NewPipeSettings;
import org.schabi.newpipe.settings.SettingsActivity;
import org.schabi.newpipe.util.ThemeHelper;
import java.io.File;
import java.util.Vector;
import us.shandian.giga.service.DownloadManagerService;
import us.shandian.giga.ui.fragment.AllMissionsFragment;
import us.shandian.giga.ui.fragment.MissionsFragment;
import us.shandian.giga.util.CrashHandler;
import us.shandian.giga.util.Utility;
public class DownloadActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
public static final String INTENT_DOWNLOAD = "us.shandian.giga.intent.DOWNLOAD";
public static final String INTENT_LIST = "us.shandian.giga.intent.LIST";
public static final String THREADS = "threads";
private static final String TAG = DownloadActivity.class.toString();
private MissionsFragment mFragment;
private String mPendingUrl;
private SharedPreferences mPrefs;
@Override
@TargetApi(21)
protected void onCreate(Bundle savedInstanceState) {
CrashHandler.init(this);
CrashHandler.register();
// Service
Intent i = new Intent();
i.setClass(this, DownloadManagerService.class);
startService(i);
super.onCreate(savedInstanceState);
ThemeHelper.setTheme(this, true);
setContentView(R.layout.activity_downloader);
//noinspection ConstantConditions
// its ok if this fails, we will catch that error later, and send it as report
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.downloads_title);
actionBar.setDisplayShowTitleEnabled(true);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// Fragment
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
updateFragments();
getWindow().getDecorView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
// Intent
if (getIntent().getAction() != null && getIntent().getAction().equals(INTENT_DOWNLOAD)) {
mPendingUrl = getIntent().getData().toString();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.getAction().equals(INTENT_DOWNLOAD)) {
mPendingUrl = intent.getData().toString();
}
}
@Override
protected void onResume() {
super.onResume();
if (mPendingUrl != null) {
showUrlDialog();
mPendingUrl = null;
}
}
private void updateFragments() {
mFragment = new AllMissionsFragment();
getFragmentManager().beginTransaction()
.replace(R.id.frame, mFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
private void showUrlDialog() {
// Create the view
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.dialog_url, null);
final EditText name = Utility.findViewById(v, R.id.file_name);
final TextView tCount = Utility.findViewById(v, R.id.threads_count);
final SeekBar threads = Utility.findViewById(v, R.id.threads);
final Toolbar toolbar = Utility.findViewById(v, R.id.toolbar);
final RadioButton audioButton = (RadioButton) Utility.findViewById(v, R.id.audio_button);
threads.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
tCount.setText(String.valueOf(progress + 1));
}
@Override
public void onStartTrackingTouch(SeekBar p1) {
}
@Override
public void onStopTrackingTouch(SeekBar p1) {
}
});
int def = mPrefs.getInt(THREADS, 4);
threads.setProgress(def - 1);
tCount.setText(String.valueOf(def));
name.setText(getIntent().getStringExtra("fileName"));
toolbar.setTitle(R.string.add);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.inflateMenu(R.menu.dialog_url);
// Show the dialog
final AlertDialog dialog = new AlertDialog.Builder(this)
.setCancelable(true)
.setView(v)
.create();
dialog.show();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.okay) {
String location;
if(audioButton.isChecked()) {
location = NewPipeSettings.getAudioDownloadPath(DownloadActivity.this);
} else {
location = NewPipeSettings.getVideoDownloadPath(DownloadActivity.this);
}
String fName = name.getText().toString().trim();
File f = new File(location, fName);
if (f.exists()) {
Toast.makeText(DownloadActivity.this, R.string.msg_exists, Toast.LENGTH_SHORT).show();
} else {
DownloadManagerService.startMission(
DownloadActivity.this,
getIntent().getData().toString(), location, fName,
audioButton.isChecked(), threads.getProgress() + 1);
mFragment.notifyChange();
mPrefs.edit().putInt(THREADS, threads.getProgress() + 1).commit();
mPendingUrl = null;
dialog.dismiss();
}
return true;
} else {
return false;
}
}
});
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.download_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home: {
onBackPressed();
return true;
}
case R.id.action_settings: {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -0,0 +1,240 @@
package org.schabi.newpipe.download;
import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import org.schabi.newpipe.App;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.settings.NewPipeSettings;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import us.shandian.giga.get.DownloadManager;
import us.shandian.giga.get.DownloadMission;
import us.shandian.giga.service.DownloadManagerService;
/**
* Created by Christian Schabesberger on 21.09.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* DownloadDialog.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class DownloadDialog extends DialogFragment {
private static final String TAG = DialogFragment.class.getName();
public static final String TITLE = "name";
public static final String FILE_SUFFIX_AUDIO = "file_suffix_audio";
public static final String FILE_SUFFIX_VIDEO = "file_suffix_video";
public static final String AUDIO_URL = "audio_url";
public static final String VIDEO_URL = "video_url";
public DownloadDialog() {
}
public static DownloadDialog newInstance(Bundle args)
{
DownloadDialog dialog = new DownloadDialog();
dialog.setArguments(args);
dialog.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
return dialog;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(ContextCompat.checkSelfPermission(this.getContext(),Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
return inflater.inflate(R.layout.dialog_url, container);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle arguments = getArguments();
final Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
final EditText name = (EditText) view.findViewById(R.id.file_name);
final TextView tCount = (TextView) view.findViewById(R.id.threads_count);
final SeekBar threads = (SeekBar) view.findViewById(R.id.threads);
toolbar.setTitle(R.string.download_dialog_title);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.inflateMenu(R.menu.dialog_url);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getDialog().dismiss();
}
});
threads.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
tCount.setText(String.valueOf(progress + 1));
}
@Override
public void onStartTrackingTouch(SeekBar p1) {
}
@Override
public void onStopTrackingTouch(SeekBar p1) {
}
});
checkDownloadOptions();
//int def = mPrefs.getInt("threads", 4);
int def = 3;
threads.setProgress(def - 1);
tCount.setText(String.valueOf(def));
name.setText(createFileName(arguments.getString(TITLE)));
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.okay) {
download();
return true;
} else {
return false;
}
}
});
}
protected void checkDownloadOptions(){
View view = getView();
Bundle arguments = getArguments();
RadioButton audioButton = (RadioButton) view.findViewById(R.id.audio_button);
RadioButton videoButton = (RadioButton) view.findViewById(R.id.video_button);
if(arguments.getString(AUDIO_URL) == null) {
audioButton.setVisibility(View.GONE);
videoButton.setChecked(true);
} else if(arguments.getString(VIDEO_URL) == null) {
videoButton.setVisibility(View.GONE);
audioButton.setChecked(true);
}
}
/**
* #143 #44 #42 #22: make shure that the filename does not contain illegal chars.
* This should fix some of the "cannot download" problems.
* */
private String createFileName(String fName) {
// from http://eng-przemelek.blogspot.de/2009/07/how-to-create-valid-file-name.html
List<String> forbiddenCharsPatterns = new ArrayList<> ();
forbiddenCharsPatterns.add("[:]+"); // Mac OS, but it looks that also Windows XP
forbiddenCharsPatterns.add("[\\*\"/\\\\\\[\\]\\:\\;\\|\\=\\,]+"); // Windows
forbiddenCharsPatterns.add("[^\\w\\d\\.]+"); // last chance... only latin letters and digits
String nameToTest = fName;
for (String pattern : forbiddenCharsPatterns) {
nameToTest = nameToTest.replaceAll(pattern, "_");
}
return nameToTest;
}
//download audio, video or both?
private void download()
{
View view = getView();
Bundle arguments = getArguments();
final EditText name = (EditText) view.findViewById(R.id.file_name);
final SeekBar threads = (SeekBar) view.findViewById(R.id.threads);
RadioButton audioButton = (RadioButton) view.findViewById(R.id.audio_button);
RadioButton videoButton = (RadioButton) view.findViewById(R.id.video_button);
String fName = name.getText().toString().trim();
boolean isAudio = audioButton.isChecked();
String url, location, filename;
if(isAudio) {
url = arguments.getString(AUDIO_URL);
location = NewPipeSettings.getAudioDownloadPath(getContext());
filename = fName + arguments.getString(FILE_SUFFIX_AUDIO);
} else {
url = arguments.getString(VIDEO_URL);
location = NewPipeSettings.getVideoDownloadPath(getContext());
filename = fName + arguments.getString(FILE_SUFFIX_VIDEO);
}
DownloadManagerService.startMission(getContext(), url, location, filename, isAudio,
threads.getProgress() + 1);
getDialog().dismiss();
}
private void download(String url, String title,
String fileSuffix, File downloadDir, Context context) {
File saveFilePath = new File(downloadDir,createFileName(title) + fileSuffix);
long id = 0;
Log.i(TAG,"Started downloading '" + url +
"' => '" + saveFilePath + "' #" + id);
if (App.isUsingTor()) {
//if using Tor, do not use DownloadManager because the proxy cannot be set
//we'll see later
FileDownloader.downloadFile(getContext(), url, saveFilePath, title);
} else {
Intent intent = new Intent(getContext(), DownloadActivity.class);
intent.setAction(DownloadActivity.INTENT_DOWNLOAD);
intent.setData(Uri.parse(url));
intent.putExtra("fileName", createFileName(title) + fileSuffix);
startActivity(intent);
}
}
}

View File

@@ -1,26 +1,21 @@
package org.schabi.newpipe;
package org.schabi.newpipe.download;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import org.schabi.newpipe.R;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import javax.net.ssl.HttpsURLConnection;
@@ -46,6 +41,8 @@ import info.guardianproject.netcipher.NetCipher;
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
// TODO: FOR HEAVEN SAKE !!! DO NOT SIMPLY USE ASYNCTASK. MAKE THIS A PROPER SERVICE !!!
public class FileDownloader extends AsyncTask<Void, Integer, Void> {
public static final String TAG = "FileDownloader";
@@ -165,5 +162,4 @@ public class FileDownloader extends AsyncTask<Void, Integer, Void> {
super.onPostExecute(aVoid);
nm.cancel(notifyId);
}
}

View File

@@ -1,105 +0,0 @@
package org.schabi.newpipe.extractor;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Vector;
/**
* Created by Christian Schabesberger on 02.02.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* DashMpdParser.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class DashMpdParser {
static class DashMpdParsingException extends ParsingException {
DashMpdParsingException(String message, Exception e) {
super(message, e);
}
}
public static List<VideoInfo.AudioStream> getAudioStreams(String dashManifestUrl,
Downloader downloader)
throws DashMpdParsingException {
String dashDoc;
try {
dashDoc = downloader.download(dashManifestUrl);
} catch(IOException ioe) {
throw new DashMpdParsingException("Could not get dash mpd: " + dashManifestUrl, ioe);
}
Vector<VideoInfo.AudioStream> audioStreams = new Vector<>();
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader(dashDoc));
String tagName = "";
String currentMimeType = "";
int currentBandwidth = -1;
int currentSamplingRate = -1;
boolean currentTagIsBaseUrl = false;
for(int eventType = parser.getEventType();
eventType != XmlPullParser.END_DOCUMENT;
eventType = parser.next() ) {
switch(eventType) {
case XmlPullParser.START_TAG:
tagName = parser.getName();
if(tagName.equals("AdaptationSet")) {
currentMimeType = parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "mimeType");
} else if(tagName.equals("Representation") && currentMimeType.contains("audio")) {
currentBandwidth = Integer.parseInt(
parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "bandwidth"));
currentSamplingRate = Integer.parseInt(
parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "audioSamplingRate"));
} else if(tagName.equals("BaseURL")) {
currentTagIsBaseUrl = true;
}
break;
case XmlPullParser.TEXT:
// actual stream tag
if(currentTagIsBaseUrl &&
(currentMimeType.contains("audio"))) {
int format = -1;
if(currentMimeType.equals(MediaFormat.WEBMA.mimeType)) {
format = MediaFormat.WEBMA.id;
} else if(currentMimeType.equals(MediaFormat.M4A.mimeType)) {
format = MediaFormat.M4A.id;
}
audioStreams.add(new VideoInfo.AudioStream(parser.getText(),
format, currentBandwidth, currentSamplingRate));
}
break;
case XmlPullParser.END_TAG:
if(tagName.equals("AdaptationSet")) {
currentMimeType = "";
} else if(tagName.equals("BaseURL")) {
currentTagIsBaseUrl = false;
}
break;
}
}
} catch(Exception e) {
throw new DashMpdParsingException("Could not parse Dash mpd", e);
}
return audioStreams;
}
}

View File

@@ -1,41 +0,0 @@
package org.schabi.newpipe.extractor;
import java.io.IOException;
/**
* Created by Christian Schabesberger on 28.01.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* Downloader.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public interface Downloader {
/**Download the text file at the supplied URL as in download(String),
* but set the HTTP header field "Accept-Language" to the supplied string.
* @param siteUrl the URL of the text file to return the contents of
* @param language the language (usually a 2-character code) to set as the preferred language
* @return the contents of the specified text file
* @throws IOException*/
String download(String siteUrl, String language) throws IOException;
/**Download (via HTTP) the text file located at the supplied URL, and return its contents.
* Primarily intended for downloading web pages.
* @param siteUrl the URL of the text file to download
* @return the contents of the specified text file
* @throws IOException*/
String download(String siteUrl) throws IOException;
}

View File

@@ -1,37 +0,0 @@
package org.schabi.newpipe.extractor;
/**
* Created by Christian Schabesberger on 30.01.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* ExctractionException.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class ExctractionException extends Exception {
public ExctractionException() {}
public ExctractionException(String message) {
super(message);
}
public ExctractionException(Throwable cause) {
super(cause);
}
public ExctractionException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -1,83 +0,0 @@
package org.schabi.newpipe.extractor;
/**
* Created by Adam Howard on 08/11/15.
*
* Copyright (c) Christian Schabesberger <chris.schabesberger@mailbox.org>
* and Adam Howard <achdisposable1@gmail.com> 2015
*
* MediaFormat.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
/**Static data about various media formats support by Newpipe, eg mime type, extension*/
public enum MediaFormat {
//video and audio combined formats
// id name suffix mime type
MPEG_4 (0x0, "MPEG-4", "mp4", "video/mp4"),
v3GPP (0x1, "3GPP", "3gp", "video/3gpp"),
WEBM (0x2, "WebM", "webm", "video/webm"),
// audio formats
M4A (0x3, "m4a", "m4a", "audio/mp4"),
WEBMA (0x4, "WebM", "webm", "audio/webm");
public final int id;
@SuppressWarnings("WeakerAccess")
public final String name;
@SuppressWarnings("WeakerAccess")
public final String suffix;
public final String mimeType;
MediaFormat(int id, String name, String suffix, String mimeType) {
this.id = id;
this.name = name;
this.suffix = suffix;
this.mimeType = mimeType;
}
/**Return the friendly name of the media format with the supplied id
* @param ident the id of the media format. Currently an arbitrary, NewPipe-specific number.
* @return the friendly name of the MediaFormat associated with this ids,
* or an empty String if none match it.*/
public static String getNameById(int ident) {
for (MediaFormat vf : MediaFormat.values()) {
if(vf.id == ident) return vf.name;
}
return "";
}
/**Return the file extension of the media format with the supplied id
* @param ident the id of the media format. Currently an arbitrary, NewPipe-specific number.
* @return the file extension of the MediaFormat associated with this ids,
* or an empty String if none match it.*/
public static String getSuffixById(int ident) {
for (MediaFormat vf : MediaFormat.values()) {
if(vf.id == ident) return vf.suffix;
}
return "";
}
/**Return the MIME type of the media format with the supplied id
* @param ident the id of the media format. Currently an arbitrary, NewPipe-specific number.
* @return the MIME type of the MediaFormat associated with this ids,
* or an empty String if none match it.*/
public static String getMimeById(int ident) {
for (MediaFormat vf : MediaFormat.values()) {
if(vf.id == ident) return vf.mimeType;
}
return "";
}
}

View File

@@ -1,60 +0,0 @@
package org.schabi.newpipe.extractor;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Christian Schabesberger on 02.02.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* Parser.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
/** avoid using regex !!! */
public class Parser {
public static class RegexException extends ParsingException {
public RegexException(String message) {
super(message);
}
}
public static String matchGroup1(String pattern, String input) throws RegexException {
Pattern pat = Pattern.compile(pattern);
Matcher mat = pat.matcher(input);
boolean foundMatch = mat.find();
if (foundMatch) {
return mat.group(1);
}
else {
//Log.e(TAG, "failed to find pattern \""+pattern+"\" inside of \""+input+"\"");
throw new RegexException("failed to find pattern \""+pattern+" inside of "+input+"\"");
}
}
public static Map<String, String> compatParseMap(final String input) throws UnsupportedEncodingException {
Map<String, String> map = new HashMap<>();
for(String arg : input.split("&")) {
String[] split_arg = arg.split("=");
map.put(split_arg[0], URLDecoder.decode(split_arg[1], "UTF-8"));
}
return map;
}
}

View File

@@ -1,42 +0,0 @@
package org.schabi.newpipe.extractor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* Created by Christian Schabesberger on 10.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* SearchEngine.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
@SuppressWarnings("ALL")
public interface SearchEngine {
class Result {
public String errorMessage = "";
public String suggestion = "";
public final List<VideoPreviewInfo> resultList = new Vector<>();
}
ArrayList<String> suggestionList(String query, Downloader dl)
throws ExctractionException, IOException;
//Result search(String query, int page);
Result search(String query, int page, String contentCountry, Downloader dl)
throws ExctractionException, IOException;
}

View File

@@ -1,54 +0,0 @@
package org.schabi.newpipe.extractor;
import android.util.Log;
import org.schabi.newpipe.extractor.services.youtube.YoutubeService;
/**
* Created by Christian Schabesberger on 23.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* ServiceList.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
/**Provides access to the video streaming services supported by NewPipe.
* Currently only Youtube until the API becomes more stable.*/
@SuppressWarnings("ALL")
public class ServiceList {
private static final String TAG = ServiceList.class.toString();
private static final StreamingService[] services = {
new YoutubeService()
};
public static StreamingService[] getServices() {
return services;
}
public static StreamingService getService(int serviceId) {
return services[serviceId];
}
public static StreamingService getService(String serviceName) {
return services[getIdOfService(serviceName)];
}
public static int getIdOfService(String serviceName) {
for(int i = 0; i < services.length; i++) {
if(services[i].getServiceInfo().name.equals(serviceName)) {
return i;
}
}
Log.e(TAG, "Error: Service " + serviceName + " not known.");
return -1;
}
}

View File

@@ -1,78 +0,0 @@
package org.schabi.newpipe.extractor;
/**
* Created by Christian Schabesberger on 10.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* StreamExtractor.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.List;
/**Scrapes information from a video streaming service (eg, YouTube).*/
@SuppressWarnings("ALL")
public interface StreamExtractor {
public class ExctractorInitException extends ExctractionException {
public ExctractorInitException() {}
public ExctractorInitException(String message) {
super(message);
}
public ExctractorInitException(Throwable cause) {
super(cause);
}
public ExctractorInitException(String message, Throwable cause) {
super(message, cause);
}
}
public class ContentNotAvailableException extends ParsingException {
public ContentNotAvailableException() {}
public ContentNotAvailableException(String message) {
super(message);
}
public ContentNotAvailableException(Throwable cause) {
super(cause);
}
public ContentNotAvailableException(String message, Throwable cause) {
super(message, cause);
}
}
public abstract int getTimeStamp() throws ParsingException;
public abstract String getTitle() throws ParsingException;
public abstract String getDescription() throws ParsingException;
public abstract String getUploader() throws ParsingException;
public abstract int getLength() throws ParsingException;
public abstract long getViews() throws ParsingException;
public abstract String getUploadDate() throws ParsingException;
public abstract String getThumbnailUrl() throws ParsingException;
public abstract String getUploaderThumbnailUrl() throws ParsingException;
public abstract List<VideoInfo.AudioStream> getAudioStreams() throws ParsingException;
public abstract List<VideoInfo.VideoStream> getVideoStreams() throws ParsingException;
public abstract List<VideoInfo.VideoStream> getVideoOnlyStreams() throws ParsingException;
public abstract String getDashMpdUrl() throws ParsingException;
public abstract int getAgeLimit() throws ParsingException;
public abstract String getAverageRating() throws ParsingException;
public abstract int getLikeCount() throws ParsingException;
public abstract int getDislikeCount() throws ParsingException;
public abstract VideoPreviewInfo getNextVideo() throws ParsingException;
public abstract List<VideoPreviewInfo> getRelatedVideos() throws ParsingException;
public abstract VideoUrlIdHandler getUrlIdConverter();
public abstract String getPageUrl();
}

View File

@@ -1,302 +0,0 @@
package org.schabi.newpipe.extractor;
import java.io.IOException;
import java.util.List;
import java.util.Vector;
/**
* Created by Christian Schabesberger on 26.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* VideoInfo.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
/**Info object for opened videos, ie the video ready to play.*/
@SuppressWarnings("ALL")
public class VideoInfo extends AbstractVideoInfo {
/**Fills out the video info fields which are common to all services.
* Probably needs to be overridden by subclasses*/
public static VideoInfo getVideoInfo(StreamExtractor extractor, Downloader downloader)
throws ExctractionException, IOException {
VideoInfo videoInfo = new VideoInfo();
videoInfo = extractImportantData(videoInfo, extractor, downloader);
videoInfo = extractStreams(videoInfo, extractor, downloader);
videoInfo = extractOptionalData(videoInfo, extractor, downloader);
return videoInfo;
}
private static VideoInfo extractImportantData(
VideoInfo videoInfo, StreamExtractor extractor, Downloader downloader)
throws ExctractionException, IOException {
/* ---- importand data, withoug the video can't be displayed goes here: ---- */
// if one of these is not available an exception is ment to be thrown directly into the frontend.
VideoUrlIdHandler uiconv = extractor.getUrlIdConverter();
videoInfo.webpage_url = extractor.getPageUrl();
videoInfo.id = uiconv.getVideoId(extractor.getPageUrl());
videoInfo.title = extractor.getTitle();
if((videoInfo.webpage_url == null || videoInfo.webpage_url.isEmpty())
|| (videoInfo.id == null || videoInfo.id.isEmpty())
|| (videoInfo.title == null /* videoInfo.title can be empty of course */));
return videoInfo;
}
private static VideoInfo extractStreams(
VideoInfo videoInfo, StreamExtractor extractor, Downloader downloader)
throws ExctractionException, IOException {
/* ---- stream extraction goes here ---- */
// At least one type of stream has to be available,
// otherwise an exception will be thrown directly into the frontend.
try {
videoInfo.dashMpdUrl = extractor.getDashMpdUrl();
} catch(Exception e) {
videoInfo.addException(new ExctractionException("Couldn't get Dash manifest", e));
}
/* Load and extract audio */
try {
videoInfo.audio_streams = extractor.getAudioStreams();
} catch(Exception e) {
videoInfo.addException(new ExctractionException("Couldn't get audio streams", e));
}
// also try to get streams from the dashMpd
if(videoInfo.dashMpdUrl != null && !videoInfo.dashMpdUrl.isEmpty()) {
if(videoInfo.audio_streams == null) {
videoInfo.audio_streams = new Vector<AudioStream>();
}
//todo: make this quick and dirty solution a real fallback
// same as the quick and dirty aboth
try {
videoInfo.audio_streams.addAll(
DashMpdParser.getAudioStreams(videoInfo.dashMpdUrl, downloader));
} catch(Exception e) {
videoInfo.addException(
new ExctractionException("Couldn't get audio streams from dash mpd", e));
}
}
/* Extract video stream url*/
try {
videoInfo.video_streams = extractor.getVideoStreams();
} catch (Exception e) {
videoInfo.addException(
new ExctractionException("Couldn't get video streams", e));
}
/* Extract video only stream url*/
try {
videoInfo.video_only_streams = extractor.getVideoOnlyStreams();
} catch(Exception e) {
videoInfo.addException(
new ExctractionException("Couldn't get video only streams", e));
}
// either dash_mpd audio_only or video has to be available, otherwise we didn't get a stream,
// and therefore failed. (Since video_only_streams are just optional they don't caunt).
if((videoInfo.video_streams == null || videoInfo.video_streams.isEmpty())
&& (videoInfo.audio_streams == null || videoInfo.audio_streams.isEmpty())
&& (videoInfo.dashMpdUrl == null || videoInfo.dashMpdUrl.isEmpty())) {
throw new ExctractionException("Could not get any stream. See error variable to get further details.");
}
return videoInfo;
}
private static VideoInfo extractOptionalData(
VideoInfo videoInfo, StreamExtractor extractor, Downloader downloader) {
/* ---- optional data goes here: ---- */
// If one of these failes, the frontend neets to handle that they are not available.
// Exceptions are therfore not thrown into the frontend, but stored into the error List,
// so the frontend can afterwads check where errors happend.
try {
videoInfo.thumbnail_url = extractor.getThumbnailUrl();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.duration = extractor.getLength();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.uploader = extractor.getUploader();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.description = extractor.getDescription();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.view_count = extractor.getViews();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.upload_date = extractor.getUploadDate();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.uploader_thumbnail_url = extractor.getUploaderThumbnailUrl();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.start_position = extractor.getTimeStamp();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.average_rating = extractor.getAverageRating();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.like_count = extractor.getLikeCount();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.dislike_count = extractor.getDislikeCount();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.next_video = extractor.getNextVideo();
} catch(Exception e) {
videoInfo.addException(e);
}
try {
videoInfo.related_videos = extractor.getRelatedVideos();
} catch(Exception e) {
videoInfo.addException(e);
}
return videoInfo;
}
public String uploader_thumbnail_url = "";
public String description = "";
public List<VideoStream> video_streams = null;
public List<AudioStream> audio_streams = null;
public List<VideoStream> video_only_streams = null;
// video streams provided by the dash mpd do not need to be provided as VideoStream.
// Later on this will also aplly to audio streams. Since dash mpd is standarized,
// crawling such a file is not service dependent. Therefore getting audio only streams by yust
// providing the dash mpd fille will be possible in the future.
public String dashMpdUrl = "";
public int duration = -1;
public int age_limit = 0;
public int like_count = -1;
public int dislike_count = -1;
public String average_rating = "";
public VideoPreviewInfo next_video = null;
public List<VideoPreviewInfo> related_videos = null;
//in seconds. some metadata is not passed using a VideoInfo object!
public int start_position = 0;
//todo: public int service_id = -1;
public List<Exception> errors = new Vector<>();
public VideoInfo() {}
/**Creates a new VideoInfo object from an existing AbstractVideoInfo.
* All the shared properties are copied to the new VideoInfo.*/
@SuppressWarnings("WeakerAccess")
public VideoInfo(AbstractVideoInfo avi) {
this.id = avi.id;
this.title = avi.title;
this.uploader = avi.uploader;
this.thumbnail_url = avi.thumbnail_url;
this.thumbnail = avi.thumbnail;
this.webpage_url = avi.webpage_url;
this.upload_date = avi.upload_date;
this.upload_date = avi.upload_date;
this.view_count = avi.view_count;
//todo: better than this
if(avi instanceof VideoPreviewInfo) {
//shitty String to convert code
String dur = ((VideoPreviewInfo)avi).duration;
int minutes = Integer.parseInt(dur.substring(0, dur.indexOf(":")));
int seconds = Integer.parseInt(dur.substring(dur.indexOf(":")+1, dur.length()));
this.duration = (minutes*60)+seconds;
}
}
public static class VideoStream {
//url of the stream
public String url = "";
public int format = -1;
public String resolution = "";
public VideoStream(String url, int format, String res) {
this.url = url; this.format = format; resolution = res;
}
// reveals wether two streams are the same, but have diferent urls
public boolean equalStats(VideoStream cmp) {
return format == cmp.format
&& resolution == cmp.resolution;
}
// revelas wether two streams are equal
public boolean equals(VideoStream cmp) {
return equalStats(cmp)
&& url == cmp.url;
}
}
@SuppressWarnings("unused")
public static class AudioStream {
public String url = "";
public int format = -1;
public int bandwidth = -1;
public int sampling_rate = -1;
public AudioStream(String url, int format, int bandwidth, int samplingRate) {
this.url = url; this.format = format;
this.bandwidth = bandwidth; this.sampling_rate = samplingRate;
}
// reveals wether two streams are the same, but have diferent urls
public boolean equalStats(AudioStream cmp) {
return format == cmp.format
&& bandwidth == cmp.bandwidth
&& sampling_rate == cmp.sampling_rate;
}
// revelas wether two streams are equal
public boolean equals(AudioStream cmp) {
return equalStats(cmp)
&& url == cmp.url;
}
}
public void addException(Exception e) {
errors.add(e);
}
}

View File

@@ -1,77 +0,0 @@
package org.schabi.newpipe.extractor;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Christian Schabesberger on 26.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* VideoPreviewInfo.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
/**Info object for previews of unopened videos, eg search results, related videos*/
public class VideoPreviewInfo extends AbstractVideoInfo implements Parcelable {
public String duration = "";
@SuppressWarnings("WeakerAccess")
protected VideoPreviewInfo(Parcel in) {
id = in.readString();
title = in.readString();
uploader = in.readString();
duration = in.readString();
thumbnail_url = in.readString();
thumbnail = (Bitmap) in.readValue(Bitmap.class.getClassLoader());
webpage_url = in.readString();
upload_date = in.readString();
view_count = in.readLong();
}
public VideoPreviewInfo() {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(uploader);
dest.writeString(duration);
dest.writeString(thumbnail_url);
dest.writeValue(thumbnail);
dest.writeString(webpage_url);
dest.writeString(upload_date);
dest.writeLong(view_count);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<VideoPreviewInfo> CREATOR = new Parcelable.Creator<VideoPreviewInfo>() {
@Override
public VideoPreviewInfo createFromParcel(Parcel in) {
return new VideoPreviewInfo(in);
}
@Override
public VideoPreviewInfo[] newArray(int size) {
return new VideoPreviewInfo[size];
}
};
}

View File

@@ -1,32 +0,0 @@
package org.schabi.newpipe.extractor;
/**
* Created by Christian Schabesberger on 02.02.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* VideoUrlIdHandler.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public interface VideoUrlIdHandler {
String getVideoUrl(String videoId);
String getVideoId(String siteUrl) throws ParsingException;
String cleanUrl(String siteUrl) throws ParsingException;
/**When a VIEW_ACTION is caught this function will test if the url delivered within the calling
Intent was meant to be watched with this Service.
Return false if this service shall not allow to be called through ACTIONs.*/
boolean acceptUrl(String videoUrl);
}

View File

@@ -1,209 +0,0 @@
package org.schabi.newpipe.extractor.services.youtube;
import android.net.Uri;
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.schabi.newpipe.extractor.Downloader;
import org.schabi.newpipe.extractor.ParsingException;
import org.schabi.newpipe.extractor.SearchEngine;
import org.schabi.newpipe.extractor.VideoPreviewInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* Created by Christian Schabesberger on 09.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* YoutubeSearchEngine.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class YoutubeSearchEngine implements SearchEngine {
private static final String TAG = YoutubeSearchEngine.class.toString();
@Override
public Result search(String query, int page, String languageCode, Downloader downloader)
throws IOException, ParsingException {
Result result = new Result();
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("www.youtube.com")
.appendPath("results")
.appendQueryParameter("search_query", query)
.appendQueryParameter("page", Integer.toString(page))
.appendQueryParameter("filters", "video");
String site;
String url = builder.build().toString();
//if we've been passed a valid language code, append it to the URL
if(!languageCode.isEmpty()) {
//assert Pattern.matches("[a-z]{2}(-([A-Z]{2}|[0-9]{1,3}))?", languageCode);
site = downloader.download(url, languageCode);
}
else {
site = downloader.download(url);
}
try {
Document doc = Jsoup.parse(site, url);
Element list = doc.select("ol[class=\"item-section\"]").first();
for (Element item : list.children()) {
/* First we need to determine which kind of item we are working with.
Youtube depicts five different kinds of items on its search result page. These are
regular videos, playlists, channels, two types of video suggestions, and a "no video
found" item. Since we only want videos, we need to filter out all the others.
An example for this can be seen here:
https://www.youtube.com/results?search_query=asdf&page=1
We already applied a filter to the url, so we don't need to care about channels and
playlists now.
*/
Element el;
// both types of spell correction item
if (!((el = item.select("div[class*=\"spell-correction\"]").first()) == null)) {
result.suggestion = el.select("a").first().text();
// search message item
} else if (!((el = item.select("div[class*=\"search-message\"]").first()) == null)) {
result.errorMessage = el.text();
// video item type
} else if (!((el = item.select("div[class*=\"yt-lockup-video\"").first()) == null)) {
VideoPreviewInfo resultItem = new VideoPreviewInfo();
Element dl = el.select("h3").first().select("a").first();
resultItem.webpage_url = dl.attr("abs:href");
try {
Pattern p = Pattern.compile("v=([0-9a-zA-Z-]*)");
Matcher m = p.matcher(resultItem.webpage_url);
resultItem.id = m.group(1);
} catch (Exception e) {
//e.printStackTrace();
}
resultItem.title = dl.text();
resultItem.duration = item.select("span[class=\"video-time\"]").first().text();
resultItem.uploader = item.select("div[class=\"yt-lockup-byline\"]").first()
.select("a").first()
.text();
resultItem.upload_date = item.select("div[class=\"yt-lockup-meta\"]").first()
.select("li").first()
.text();
//todo: test against view_count
String viewCountInfo = item.select("div[class=\"yt-lockup-meta\"]").first()
.select("li").get(1)
.text();
viewCountInfo = viewCountInfo.substring(0, viewCountInfo.indexOf(' '));
viewCountInfo = viewCountInfo.replaceAll("[,.]", "");
resultItem.view_count = Long.parseLong(viewCountInfo);
Element te = item.select("div[class=\"yt-thumb video-thumb\"]").first()
.select("img").first();
resultItem.thumbnail_url = te.attr("abs:src");
// Sometimes youtube sends links to gif files which somehow seem to not exist
// anymore. Items with such gif also offer a secondary image source. So we are going
// to use that if we've caught such an item.
if (resultItem.thumbnail_url.contains(".gif")) {
resultItem.thumbnail_url = te.attr("abs:data-thumb");
}
result.resultList.add(resultItem);
} else {
//noinspection ConstantConditions
Log.e(TAG, "unexpected element found:\"" + el + "\"");
}
}
} catch(Exception e) {
throw new ParsingException(e);
}
return result;
}
@Override
public ArrayList<String> suggestionList(String query, Downloader dl)
throws IOException, ParsingException {
ArrayList<String> suggestions = new ArrayList<>();
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("suggestqueries.google.com")
.appendPath("complete")
.appendPath("search")
.appendQueryParameter("client", "")
.appendQueryParameter("output", "toolbar")
.appendQueryParameter("ds", "yt")
.appendQueryParameter("q", query);
String url = builder.build().toString();
String response = dl.download(url);
try {
//TODO: Parse xml data using Jsoup not done
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
org.w3c.dom.Document doc = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(new InputSource(
new ByteArrayInputStream(response.getBytes("utf-8"))));
doc.getDocumentElement().normalize();
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
if (doc != null) {
NodeList nList = doc.getElementsByTagName("CompleteSuggestion");
for (int temp = 0; temp < nList.getLength(); temp++) {
NodeList nList1 = doc.getElementsByTagName("suggestion");
Node nNode1 = nList1.item(temp);
if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element eElement = (org.w3c.dom.Element) nNode1;
suggestions.add(eElement.getAttribute("data"));
}
}
} else {
Log.e(TAG, "GREAT FUCKING ERROR");
}
return suggestions;
} catch(Exception e) {
throw new ParsingException(e);
}
}
}

View File

@@ -1,60 +0,0 @@
package org.schabi.newpipe.extractor.services.youtube;
import org.schabi.newpipe.extractor.ExctractionException;
import org.schabi.newpipe.extractor.Downloader;
import org.schabi.newpipe.extractor.StreamExtractor;
import org.schabi.newpipe.extractor.StreamingService;
import org.schabi.newpipe.extractor.VideoUrlIdHandler;
import org.schabi.newpipe.extractor.SearchEngine;
import java.io.IOException;
/**
* Created by Christian Schabesberger on 23.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* YoutubeService.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class YoutubeService implements StreamingService {
@Override
public ServiceInfo getServiceInfo() {
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.name = "Youtube";
return serviceInfo;
}
@Override
public StreamExtractor getExtractorInstance(String url, Downloader downloader)
throws ExctractionException, IOException {
VideoUrlIdHandler urlIdHandler = new YoutubeVideoUrlIdHandler();
if(urlIdHandler.acceptUrl(url)) {
return new YoutubeStreamExtractor(url, downloader) ;
}
else {
throw new IllegalArgumentException("supplied String is not a valid Youtube URL");
}
}
@Override
public SearchEngine getSearchEngineInstance() {
return new YoutubeSearchEngine();
}
@Override
public VideoUrlIdHandler getUrlIdHandler() {
return new YoutubeVideoUrlIdHandler();
}
}

View File

@@ -1,696 +0,0 @@
package org.schabi.newpipe.extractor.services.youtube;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.ScriptableObject;
import org.schabi.newpipe.extractor.ExctractionException;
import org.schabi.newpipe.extractor.Downloader;
import org.schabi.newpipe.extractor.Parser;
import org.schabi.newpipe.extractor.ParsingException;
import org.schabi.newpipe.extractor.VideoUrlIdHandler;
import org.schabi.newpipe.extractor.StreamExtractor;
import org.schabi.newpipe.extractor.MediaFormat;
import org.schabi.newpipe.extractor.VideoInfo;
import org.schabi.newpipe.extractor.VideoPreviewInfo;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
* Created by Christian Schabesberger on 06.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* YoutubeStreamExtractor.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class YoutubeStreamExtractor implements StreamExtractor {
// Sometimes if the html page of youtube is already downloaded, youtube web page will internally
// download the /get_video_info page. Since a certain date dashmpd url is only available over
// this /get_video_info page, so we always need to download this one to.
// %%video_id%% will be replaced by the actual video id
// $$el_type$$ will be replaced by the actual el_type (se the declarations below)
private static final String GET_VIDEO_INFO_URL =
"https://www.youtube.com/get_video_info?video_id=%%video_id%%$$el_type$$&ps=default&eurl=&gl=US&hl=en";
// eltype is nececeary for the url aboth
private static final String EL_INFO = "el=info";
public enum ItagType {
AUDIO,
VIDEO,
VIDEO_ONLY
}
private static class ItagItem {
public ItagItem(int id, ItagType type, MediaFormat format, String res, int fps) {
this.id = id;
this.itagType = type;
this.mediaFormatId = format.id;
this.resolutionString = res;
this.fps = fps;
}
public ItagItem(int id, ItagType type, MediaFormat format, int samplingRate, int bandWidth) {
this.id = id;
this.itagType = type;
this.mediaFormatId = format.id;
this.samplingRate = samplingRate;
this.bandWidth = bandWidth;
}
public int id;
public ItagType itagType;
public int mediaFormatId;
public String resolutionString = null;
public int fps = -1;
public int samplingRate = -1;
public int bandWidth = -1;
}
private static final ItagItem[] itagList = {
// video streams
// id, ItagType, MediaFormat, Resolution, fps
new ItagItem(17, ItagType.VIDEO, MediaFormat.v3GPP, "144p", 12),
new ItagItem(18, ItagType.VIDEO, MediaFormat.MPEG_4, "360p", 24),
new ItagItem(22, ItagType.VIDEO, MediaFormat.MPEG_4, "720p", 24),
new ItagItem(36, ItagType.VIDEO, MediaFormat.v3GPP, "240p", 24),
new ItagItem(37, ItagType.VIDEO, MediaFormat.MPEG_4, "1080p", 24),
new ItagItem(38, ItagType.VIDEO, MediaFormat.MPEG_4, "1080p", 24),
new ItagItem(43, ItagType.VIDEO, MediaFormat.WEBM, "360p", 24),
new ItagItem(44, ItagType.VIDEO, MediaFormat.WEBM, "480p", 24),
new ItagItem(45, ItagType.VIDEO, MediaFormat.WEBM, "720p", 24),
new ItagItem(46, ItagType.VIDEO, MediaFormat.WEBM, "1080p", 24),
// audio streams
// id, ItagType, MediaFormat, samplingR, bandwidth
new ItagItem(249, ItagType.AUDIO, MediaFormat.WEBMA, 0, 0), // bandwith/samplingR 0 because not known
new ItagItem(250, ItagType.AUDIO, MediaFormat.WEBMA, 0, 0),
new ItagItem(171, ItagType.AUDIO, MediaFormat.WEBMA, 0, 0),
new ItagItem(140, ItagType.AUDIO, MediaFormat.M4A, 0, 0),
new ItagItem(251, ItagType.AUDIO, MediaFormat.WEBMA, 0, 0),
// video only streams
new ItagItem(160, ItagType.VIDEO_ONLY, MediaFormat.MPEG_4, "144p", 24),
new ItagItem(133, ItagType.VIDEO_ONLY, MediaFormat.MPEG_4, "240p", 24),
new ItagItem(134, ItagType.VIDEO_ONLY, MediaFormat.MPEG_4, "360p", 24),
new ItagItem(135, ItagType.VIDEO_ONLY, MediaFormat.MPEG_4, "480p", 24),
new ItagItem(136, ItagType.VIDEO_ONLY, MediaFormat.MPEG_4, "720p", 24),
new ItagItem(137, ItagType.VIDEO_ONLY, MediaFormat.MPEG_4, "1080p", 24),
};
/**These lists only contain itag formats that are supported by the common Android Video player.
However if you are looking for a list showing all itag formats, look at
https://github.com/rg3/youtube-dl/issues/1687 */
public static boolean itagIsSupported(int itag) {
for(ItagItem item : itagList) {
if(itag == item.id) {
return true;
}
}
return false;
}
public static ItagItem getItagItem(int itag) throws ParsingException {
for(ItagItem item : itagList) {
if(itag == item.id) {
return item;
}
}
throw new ParsingException("itag=" + Integer.toString(itag) + " not supported");
}
public class DecryptException extends ParsingException {
DecryptException(Throwable cause) {
super(cause);
}
DecryptException(String message, Throwable cause) {
super(message, cause);
}
}
// special content not available exceptions
public class GemaException extends ContentNotAvailableException {
GemaException(String message) {
super(message);
}
}
// ----------------
private static final String TAG = YoutubeStreamExtractor.class.toString();
private final Document doc;
private JSONObject playerArgs;
//private Map<String, String> videoInfoPage;
// static values
private static final String DECRYPTION_FUNC_NAME="decrypt";
// cached values
private static volatile String decryptionCode = "";
VideoUrlIdHandler urlidhandler = new YoutubeVideoUrlIdHandler();
String pageUrl = "";
private Downloader downloader;
public YoutubeStreamExtractor(String pageUrl, Downloader dl) throws ExctractionException, IOException {
//most common videoInfo fields are now set in our superclass, for all services
downloader = dl;
this.pageUrl = pageUrl;
String pageContent = downloader.download(urlidhandler.cleanUrl(pageUrl));
doc = Jsoup.parse(pageContent, pageUrl);
String ytPlayerConfigRaw;
JSONObject ytPlayerConfig;
//attempt to load the youtube js player JSON arguments
try {
ytPlayerConfigRaw =
Parser.matchGroup1("ytplayer.config\\s*=\\s*(\\{.*?\\});", pageContent);
ytPlayerConfig = new JSONObject(ytPlayerConfigRaw);
playerArgs = ytPlayerConfig.getJSONObject("args");
} catch (Parser.RegexException e) {
String errorReason = findErrorReason(doc);
switch(errorReason) {
case "GEMA":
throw new GemaException(errorReason);
case "":
throw new ParsingException("player config empty", e);
default:
throw new ContentNotAvailableException("Content not available", e);
}
} catch (JSONException e) {
throw new ParsingException("Could not parse yt player config");
}
/* not yet nececeary
// get videoInfo page
try {
//Parser.unescapeEntities(url_data_str, true).split("&")
String getVideoInfoUrl = GET_VIDEO_INFO_URL.replace("%%video_id%%",
urlidhandler.getVideoId(pageUrl)).replace("$$el_type$$", "&" + EL_INFO);
videoInfoPage = Parser.compatParseMap(downloader.download(getVideoInfoUrl));
} catch(Exception e) {
throw new ParsingException("Could not load video info page.", e);
}
*/
//----------------------------------
// load and parse description code, if it isn't already initialised
//----------------------------------
if (decryptionCode.isEmpty()) {
try {
// The Youtube service needs to be initialized by downloading the
// js-Youtube-player. This is done in order to get the algorithm
// for decrypting cryptic signatures inside certain stream urls.
JSONObject ytAssets = ytPlayerConfig.getJSONObject("assets");
String playerUrl = ytAssets.getString("js");
if (playerUrl.startsWith("//")) {
playerUrl = "https:" + playerUrl;
}
decryptionCode = loadDecryptionCode(playerUrl);
} catch (JSONException e) {
throw new ParsingException(
"Could not load decryption code for the Youtube service.", e);
}
}
}
@Override
public String getTitle() throws ParsingException {
try {//json player args method
return playerArgs.getString("title");
} catch(JSONException je) {//html <meta> method
je.printStackTrace();
Log.w(TAG, "failed to load title from JSON args; trying to extract it from HTML");
try { // fall through to fall-back
return doc.select("meta[name=title]").attr("content");
} catch (Exception e) {
throw new ParsingException("failed permanently to load title.", e);
}
}
}
@Override
public String getDescription() throws ParsingException {
try {
return doc.select("p[id=\"eow-description\"]").first().html();
} catch (Exception e) {//todo: add fallback method <-- there is no ... as long as i know
throw new ParsingException("failed to load description.", e);
}
}
@Override
public String getUploader() throws ParsingException {
try {//json player args method
return playerArgs.getString("author");
} catch(JSONException je) {
je.printStackTrace();
Log.w(TAG,
"failed to load uploader name from JSON args; trying to extract it from HTML");
} try {//fall through to fallback HTML method
return doc.select("div.yt-user-info").first().text();
} catch (Exception e) {
throw new ParsingException("failed permanently to load uploader name.", e);
}
}
@Override
public int getLength() throws ParsingException {
try {
return playerArgs.getInt("length_seconds");
} catch (JSONException e) {//todo: find fallback method
throw new ParsingException("failed to load video duration from JSON args", e);
}
}
@Override
public long getViews() throws ParsingException {
try {
String viewCountString = doc.select("meta[itemprop=interactionCount]").attr("content");
return Long.parseLong(viewCountString);
} catch (Exception e) {//todo: find fallback method
throw new ParsingException("failed to number of views", e);
}
}
@Override
public String getUploadDate() throws ParsingException {
try {
return doc.select("meta[itemprop=datePublished]").attr("content");
} catch (Exception e) {//todo: add fallback method
throw new ParsingException("failed to get upload date.", e);
}
}
@Override
public String getThumbnailUrl() throws ParsingException {
//first attempt getting a small image version
//in the html extracting part we try to get a thumbnail with a higher resolution
// Try to get high resolution thumbnail if it fails use low res from the player instead
try {
return doc.select("link[itemprop=\"thumbnailUrl\"]").first().attr("abs:href");
} catch(Exception e) {
Log.w(TAG, "Could not find high res Thumbnail. Using low res instead");
}
try { //fall through to fallback
return playerArgs.getString("thumbnail_url");
} catch (JSONException je) {
throw new ParsingException(
"failed to extract thumbnail URL from JSON args; trying to extract it from HTML", je);
}
}
@Override
public String getUploaderThumbnailUrl() throws ParsingException {
try {
return doc.select("a[class*=\"yt-user-photo\"]").first()
.select("img").first()
.attr("abs:data-thumb");
} catch (Exception e) {//todo: add fallback method
throw new ParsingException("failed to get uploader thumbnail URL.", e);
}
}
@Override
public String getDashMpdUrl() throws ParsingException {
/*
try {
String dashManifestUrl = videoInfoPage.get("dashmpd");
if(!dashManifestUrl.contains("/signature/")) {
String encryptedSig = Parser.matchGroup1("/s/([a-fA-F0-9\\.]+)", dashManifestUrl);
String decryptedSig;
decryptedSig = decryptSignature(encryptedSig, decryptionCode);
dashManifestUrl = dashManifestUrl.replace("/s/" + encryptedSig, "/signature/" + decryptedSig);
}
return dashManifestUrl;
} catch (Exception e) {
throw new ParsingException(
"Could not get \"dashmpd\" maybe VideoInfoPage is broken.", e);
}
*/
return "";
}
@Override
public List<VideoInfo.AudioStream> getAudioStreams() throws ParsingException {
Vector<VideoInfo.AudioStream> audioStreams = new Vector<>();
try{
String encoded_url_map = playerArgs.getString("adaptive_fmts");
for(String url_data_str : encoded_url_map.split(",")) {
// This loop iterates through multiple streams, therefor tags
// is related to one and the same stream at a time.
Map<String, String> tags = Parser.compatParseMap(
org.jsoup.parser.Parser.unescapeEntities(url_data_str, true));
int itag = Integer.parseInt(tags.get("itag"));
if (itagIsSupported(itag)) {
ItagItem itagItem = getItagItem(itag);
if (itagItem.itagType == ItagType.AUDIO) {
String streamUrl = tags.get("url");
// if video has a signature: decrypt it and add it to the url
if (tags.get("s") != null) {
streamUrl = streamUrl + "&signature="
+ decryptSignature(tags.get("s"), decryptionCode);
}
audioStreams.add(new VideoInfo.AudioStream(streamUrl,
itagItem.mediaFormatId,
itagItem.bandWidth,
itagItem.samplingRate));
}
}
}
} catch (Exception e) {
throw new ParsingException("Could not get audiostreams", e);
}
return audioStreams;
}
@Override
public List<VideoInfo.VideoStream> getVideoStreams() throws ParsingException {
Vector<VideoInfo.VideoStream> videoStreams = new Vector<>();
try{
String encoded_url_map = playerArgs.getString("url_encoded_fmt_stream_map");
for(String url_data_str : encoded_url_map.split(",")) {
try {
// This loop iterates through multiple streams, therefor tags
// is related to one and the same stream at a time.
Map<String, String> tags = Parser.compatParseMap(
org.jsoup.parser.Parser.unescapeEntities(url_data_str, true));
int itag = Integer.parseInt(tags.get("itag"));
if (itagIsSupported(itag)) {
ItagItem itagItem = getItagItem(itag);
if(itagItem.itagType == ItagType.VIDEO) {
String streamUrl = tags.get("url");
// if video has a signature: decrypt it and add it to the url
if (tags.get("s") != null) {
streamUrl = streamUrl + "&signature="
+ decryptSignature(tags.get("s"), decryptionCode);
}
videoStreams.add(new VideoInfo.VideoStream(
streamUrl,
itagItem.mediaFormatId,
itagItem.resolutionString));
}
}
} catch (Exception e) {
Log.w(TAG, "Could not get Video stream.");
e.printStackTrace();
}
}
} catch (Exception e) {
throw new ParsingException("Failed to get video streams", e);
}
if(videoStreams.isEmpty()) {
throw new ParsingException("Failed to get any video stream");
}
return videoStreams;
}
@Override
public List<VideoInfo.VideoStream> getVideoOnlyStreams() throws ParsingException {
return null;
}
/**Attempts to parse (and return) the offset to start playing the video from.
* @return the offset (in seconds), or 0 if no timestamp is found.*/
@Override
public int getTimeStamp() throws ParsingException {
String timeStamp;
try {
timeStamp = Parser.matchGroup1("((#|&|\\?)t=\\d{0,3}h?\\d{0,3}m?\\d{1,3}s?)", pageUrl);
} catch (Parser.RegexException e) {
// catch this instantly since an url does not necessarily have to have a time stamp
// -2 because well the testing system will then know its the regex that failed :/
// not good i know
return -2;
}
if(!timeStamp.isEmpty()) {
try {
String secondsString = "";
String minutesString = "";
String hoursString = "";
try {
secondsString = Parser.matchGroup1("(\\d{1,3})s", timeStamp);
minutesString = Parser.matchGroup1("(\\d{1,3})m", timeStamp);
hoursString = Parser.matchGroup1("(\\d{1,3})h", timeStamp);
} catch (Exception e) {
//it could be that time is given in another method
if (secondsString.isEmpty() //if nothing was got,
&& minutesString.isEmpty()//treat as unlabelled seconds
&& hoursString.isEmpty()) {
secondsString = Parser.matchGroup1("t=(\\d{1,3})", timeStamp);
}
}
int seconds = (secondsString.isEmpty() ? 0 : Integer.parseInt(secondsString));
int minutes = (minutesString.isEmpty() ? 0 : Integer.parseInt(minutesString));
int hours = (hoursString.isEmpty() ? 0 : Integer.parseInt(hoursString));
int ret = seconds + (60 * minutes) + (3600 * hours);//don't trust BODMAS!
//Log.d(TAG, "derived timestamp value:"+ret);
return ret;
//the ordering varies internationally
} catch (ParsingException e) {
throw new ParsingException("Could not get timestamp.", e);
}
} else {
return 0;
}
}
@Override
public int getAgeLimit() throws ParsingException {
// Not yet implemented.
// Also you need to be logged in to see age restricted videos on youtube,
// therefore NP is not able to receive such videos.
return 0;
}
@Override
public String getAverageRating() throws ParsingException {
try {
return playerArgs.getString("avg_rating");
} catch (JSONException e) {
throw new ParsingException("Could not get Average rating", e);
}
}
@Override
public int getLikeCount() throws ParsingException {
String likesString = "";
try {
likesString = doc.select("button.like-button-renderer-like-button").first()
.select("span.yt-uix-button-content").first().text();
return Integer.parseInt(likesString.replaceAll("[^\\d]", ""));
} catch (NumberFormatException nfe) {
throw new ParsingException(
"failed to parse likesString \"" + likesString + "\" as integers", nfe);
} catch (Exception e) {
throw new ParsingException("Could not get like count", e);
}
}
@Override
public int getDislikeCount() throws ParsingException {
String dislikesString = "";
try {
dislikesString = doc.select("button.like-button-renderer-dislike-button").first()
.select("span.yt-uix-button-content").first().text();
return Integer.parseInt(dislikesString.replaceAll("[^\\d]", ""));
} catch(NumberFormatException nfe) {
throw new ParsingException(
"failed to parse dislikesString \"" + dislikesString + "\" as integers", nfe);
} catch(Exception e) {
throw new ParsingException("Could not get dislike count", e);
}
}
@Override
public VideoPreviewInfo getNextVideo() throws ParsingException {
try {
return extractVideoPreviewInfo(doc.select("div[class=\"watch-sidebar-section\"]").first()
.select("li").first());
} catch(Exception e) {
throw new ParsingException("Could not get next video", e);
}
}
@Override
public Vector<VideoPreviewInfo> getRelatedVideos() throws ParsingException {
try {
Vector<VideoPreviewInfo> relatedVideos = new Vector<>();
for (Element li : doc.select("ul[id=\"watch-related\"]").first().children()) {
// first check if we have a playlist. If so leave them out
if (li.select("a[class*=\"content-link\"]").first() != null) {
relatedVideos.add(extractVideoPreviewInfo(li));
}
}
return relatedVideos;
} catch(Exception e) {
throw new ParsingException("Could not get related videos", e);
}
}
@Override
public VideoUrlIdHandler getUrlIdConverter() {
return new YoutubeVideoUrlIdHandler();
}
@Override
public String getPageUrl() {
return pageUrl;
}
/**Provides information about links to other videos on the video page, such as related videos.
* This is encapsulated in a VideoPreviewInfo object,
* which is a subset of the fields in a full VideoInfo.*/
private VideoPreviewInfo extractVideoPreviewInfo(Element li) throws ParsingException {
VideoPreviewInfo info = new VideoPreviewInfo();
try {
info.webpage_url = li.select("a.content-link").first()
.attr("abs:href");
info.id = Parser.matchGroup1("v=([0-9a-zA-Z-]*)", info.webpage_url);
//todo: check NullPointerException causing
info.title = li.select("span.title").first().text();
//this page causes the NullPointerException, after finding it by searching for "tjvg":
//https://www.youtube.com/watch?v=Uqg0aEhLFAg
//this line is unused
//String views = li.select("span.view-count").first().text();
//Log.i(TAG, "title:"+info.title);
//Log.i(TAG, "view count:"+views);
try {
info.view_count = Long.parseLong(li.select("span.view-count")
.first().text().replaceAll("[^\\d]", ""));
} catch (NullPointerException e) {//related videos sometimes have no view count
info.view_count = 0;
}
info.uploader = li.select("span.g-hovercard").first().text();
info.duration = li.select("span.video-time").first().text();
Element img = li.select("img").first();
info.thumbnail_url = img.attr("abs:src");
// Sometimes youtube sends links to gif files which somehow seem to not exist
// anymore. Items with such gif also offer a secondary image source. So we are going
// to use that if we caught such an item.
if (info.thumbnail_url.contains(".gif")) {
info.thumbnail_url = img.attr("data-thumb");
}
if (info.thumbnail_url.startsWith("//")) {
info.thumbnail_url = "https:" + info.thumbnail_url;
}
} catch (Exception e) {
throw new ParsingException(e);
}
return info;
}
private String loadDecryptionCode(String playerUrl) throws DecryptException {
String decryptionFuncName;
String decryptionFunc;
String helperObjectName;
String helperObject;
String callerFunc = "function " + DECRYPTION_FUNC_NAME + "(a){return %%(a);}";
String decryptionCode;
try {
String playerCode = downloader.download(playerUrl);
decryptionFuncName =
Parser.matchGroup1("\\.sig\\|\\|([a-zA-Z0-9$]+)\\(", playerCode);
String functionPattern = "("
+ decryptionFuncName.replace("$", "\\$")
+ "=function\\([a-zA-Z0-9_]*\\)\\{.+?\\})";
decryptionFunc = "var " + Parser.matchGroup1(functionPattern, playerCode) + ";";
helperObjectName = Parser
.matchGroup1(";([A-Za-z0-9_\\$]{2})\\...\\(", decryptionFunc);
String helperPattern = "(var "
+ helperObjectName.replace("$", "\\$") + "=\\{.+?\\}\\};)";
helperObject = Parser.matchGroup1(helperPattern, playerCode);
callerFunc = callerFunc.replace("%%", decryptionFuncName);
decryptionCode = helperObject + decryptionFunc + callerFunc;
} catch(IOException ioe) {
throw new DecryptException("Could not load decrypt function", ioe);
} catch(Exception e) {
throw new DecryptException("Could not parse decrypt function ", e);
}
return decryptionCode;
}
private String decryptSignature(String encryptedSig, String decryptionCode)
throws DecryptException{
Context context = Context.enter();
context.setOptimizationLevel(-1);
Object result = null;
try {
ScriptableObject scope = context.initStandardObjects();
context.evaluateString(scope, decryptionCode, "decryptionCode", 1, null);
Function decryptionFunc = (Function) scope.get("decrypt", scope);
result = decryptionFunc.call(context, scope, scope, new Object[]{encryptedSig});
} catch (Exception e) {
throw new DecryptException(e);
} finally {
Context.exit();
}
return (result == null ? "" : result.toString());
}
private String findErrorReason(Document doc) {
String errorMessage = doc.select("h1[id=\"unavailable-message\"]").first().text();
if(errorMessage.contains("GEMA")) {
// Gema sometimes blocks youtube music content in germany:
// https://www.gema.de/en/
// Detailed description:
// https://en.wikipedia.org/wiki/GEMA_%28German_organization%29
return "GEMA";
}
return "";
}
}

View File

@@ -1,80 +0,0 @@
package org.schabi.newpipe.extractor.services.youtube;
import org.schabi.newpipe.extractor.Parser;
import org.schabi.newpipe.extractor.ParsingException;
import org.schabi.newpipe.extractor.VideoUrlIdHandler;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
/**
* Created by Christian Schabesberger on 02.02.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* YoutubeVideoUrlIdHandler.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class YoutubeVideoUrlIdHandler implements VideoUrlIdHandler {
@SuppressWarnings("WeakerAccess")
@Override
public String getVideoUrl(String videoId) {
return "https://www.youtube.com/watch?v=" + videoId;
}
@SuppressWarnings("WeakerAccess")
@Override
public String getVideoId(String url) throws ParsingException {
String id = "";
if(url.contains("youtube")) {
if(url.contains("attribution_link")) {
try {
String escapedQuery = Parser.matchGroup1("u=(.[^&|$]*)", url);
String query = URLDecoder.decode(escapedQuery, "UTF-8");
id = Parser.matchGroup1("v=([\\-a-zA-Z0-9_]{11})", query);
} catch(UnsupportedEncodingException uee) {
throw new ParsingException("Could not parse attribution_link", uee);
}
} else {
id = Parser.matchGroup1("youtube\\.com/watch\\?v=([\\-a-zA-Z0-9_]{11})", url);
}
}
else if(url.contains("youtu.be")) {
id = Parser.matchGroup1("youtu\\.be/([a-zA-Z0-9_-]{11})", url);
}
else {
throw new ParsingException("Error no suitable url: " + url);
}
if(!id.isEmpty()){
//Log.i(TAG, "string \""+url+"\" matches!");
return id;
} else {
throw new ParsingException("Error could not parse url: " + url);
}
}
public String cleanUrl(String complexUrl) throws ParsingException {
return getVideoUrl(getVideoId(complexUrl));
}
@Override
public boolean acceptUrl(String videoUrl) {
return videoUrl.contains("youtube") ||
videoUrl.contains("youtu.be");
}
}

View File

@@ -0,0 +1,10 @@
package org.schabi.newpipe.fragments;
import org.schabi.newpipe.extractor.StreamingService;
/**
* Interface for communication purposes between activity and fragment
*/
public interface OnItemSelectedListener {
void onItemSelected(StreamingService.LinkType linkType, int serviceId, String url, String name);
}

View File

@@ -0,0 +1,421 @@
package org.schabi.newpipe.fragments.channel;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.schabi.newpipe.ImageErrorLoadingListener;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.extractor.channel.ChannelInfo;
import org.schabi.newpipe.fragments.OnItemSelectedListener;
import org.schabi.newpipe.info_list.InfoItemBuilder;
import org.schabi.newpipe.info_list.InfoListAdapter;
import org.schabi.newpipe.report.ErrorActivity;
import org.schabi.newpipe.util.Constants;
import org.schabi.newpipe.util.NavigationHelper;
import org.schabi.newpipe.workers.ChannelExtractorWorker;
import java.text.NumberFormat;
import static android.os.Build.VERSION.SDK_INT;
/**
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* ChannelFragment.java is part of NewPipe.
* <p>
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class ChannelFragment extends Fragment implements ChannelExtractorWorker.OnChannelInfoReceive {
private static final String TAG = "ChannelFragment";
private AppCompatActivity activity;
private OnItemSelectedListener onItemSelectedListener;
private InfoListAdapter infoListAdapter;
private ChannelExtractorWorker currentExtractorWorker;
private ChannelInfo currentChannelInfo;
private int serviceId = -1;
private String channelName = "";
private String channelUrl = "";
private boolean isLoading = false;
private int pageNumber = 0;
private boolean hasNextPage = true;
private ImageLoader imageLoader = ImageLoader.getInstance();
/*//////////////////////////////////////////////////////////////////////////
// Views
//////////////////////////////////////////////////////////////////////////*/
private View rootView = null;
private RecyclerView channelVideosList;
private LinearLayoutManager layoutManager;
private ProgressBar loadingProgressBar;
private View headerRootLayout;
private ImageView headerChannelBanner;
private ImageView headerAvatarView;
private TextView headerTitleView;
private TextView headerSubscriberView;
private Button headerSubscriberButton;
private View headerSubscriberLayout;
/*////////////////////////////////////////////////////////////////////////*/
public ChannelFragment() {
}
public static ChannelFragment newInstance(int serviceId, String url, String name) {
ChannelFragment instance = newInstance();
Bundle bundle = new Bundle();
bundle.putString(Constants.KEY_URL, url);
bundle.putString(Constants.KEY_TITLE, name);
bundle.putInt(Constants.KEY_SERVICE_ID, serviceId);
instance.setArguments(bundle);
return instance;
}
public static ChannelFragment newInstance() {
return new ChannelFragment();
}
/*//////////////////////////////////////////////////////////////////////////
// Fragment's LifeCycle
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = ((AppCompatActivity) context);
onItemSelectedListener = ((OnItemSelectedListener) context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
isLoading = false;
if (savedInstanceState != null) {
channelUrl = savedInstanceState.getString(Constants.KEY_URL);
channelName = savedInstanceState.getString(Constants.KEY_TITLE);
serviceId = savedInstanceState.getInt(Constants.KEY_SERVICE_ID, -1);
} else {
try {
Bundle args = getArguments();
if (args != null) {
channelUrl = args.getString(Constants.KEY_URL);
channelName = args.getString(Constants.KEY_TITLE);
serviceId = args.getInt(Constants.KEY_SERVICE_ID, 0);
}
} catch (Exception e) {
e.printStackTrace();
ErrorActivity.reportError(getActivity(), e, null,
getActivity().findViewById(android.R.id.content),
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
NewPipe.getNameOfService(serviceId),
"", R.string.general_error));
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_channel, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
loadingProgressBar = (ProgressBar) view.findViewById(R.id.loading_progress_bar);
channelVideosList = (RecyclerView) view.findViewById(R.id.channel_streams_view);
infoListAdapter = new InfoListAdapter(activity, rootView);
layoutManager = new LinearLayoutManager(activity);
channelVideosList.setLayoutManager(layoutManager);
headerRootLayout = activity.getLayoutInflater().inflate(R.layout.channel_header, channelVideosList, false);
infoListAdapter.setHeader(headerRootLayout);
infoListAdapter.setFooter(activity.getLayoutInflater().inflate(R.layout.pignate_footer, channelVideosList, false));
channelVideosList.setAdapter(infoListAdapter);
headerChannelBanner = (ImageView) headerRootLayout.findViewById(R.id.channel_banner_image);
headerAvatarView = (ImageView) headerRootLayout.findViewById(R.id.channel_avatar_view);
headerTitleView = (TextView) headerRootLayout.findViewById(R.id.channel_title_view);
headerSubscriberView = (TextView) headerRootLayout.findViewById(R.id.channel_subscriber_view);
headerSubscriberButton = (Button) headerRootLayout.findViewById(R.id.channel_subscribe_button);
headerSubscriberLayout = headerRootLayout.findViewById(R.id.channel_subscriber_layout);
initListeners();
isLoading = true;
}
@Override
public void onDestroyView() {
super.onDestroyView();
headerAvatarView.setImageBitmap(null);
headerChannelBanner.setImageBitmap(null);
channelVideosList.removeAllViews();
rootView = null;
channelVideosList = null;
layoutManager = null;
loadingProgressBar = null;
headerRootLayout = null;
headerChannelBanner = null;
headerAvatarView = null;
headerTitleView = null;
headerSubscriberView = null;
headerSubscriberButton = null;
headerSubscriberLayout = null;
}
@Override
public void onResume() {
super.onResume();
if (isLoading) {
requestData(false);
}
}
@Override
public void onStop() {
super.onStop();
if (currentExtractorWorker != null) currentExtractorWorker.cancel();
}
@Override
public void onDestroy() {
super.onDestroy();
imageLoader.clearMemoryCache();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(Constants.KEY_URL, channelUrl);
outState.putString(Constants.KEY_TITLE, channelName);
outState.putInt(Constants.KEY_SERVICE_ID, serviceId);
}
/*//////////////////////////////////////////////////////////////////////////
// Menu
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_channel, menu);
ActionBar supportActionBar = activity.getSupportActionBar();
if (supportActionBar != null) {
supportActionBar.setDisplayShowTitleEnabled(true);
supportActionBar.setDisplayHomeAsUpEnabled(true);
//noinspection deprecation
supportActionBar.setNavigationMode(0);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_item_openInBrowser: {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(channelUrl));
startActivity(Intent.createChooser(intent, getString(R.string.choose_browser)));
return true;
}
case R.id.menu_item_share:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, channelUrl);
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, getString(R.string.share_dialog_title)));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/*//////////////////////////////////////////////////////////////////////////
// Init's
//////////////////////////////////////////////////////////////////////////*/
private void initListeners() {
infoListAdapter.setOnStreamInfoItemSelectedListener(new InfoItemBuilder.OnInfoItemSelectedListener() {
@Override
public void selected(int serviceId, String url, String title) {
NavigationHelper.openVideoDetail(onItemSelectedListener, serviceId, url, title);
}
});
// detect if list has ben scrolled to the bottom
channelVideosList.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int pastVisiblesItems, visibleItemCount, totalItemCount;
super.onScrolled(recyclerView, dx, dy);
//check for scroll down
if (dy > 0) {
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && !currentExtractorWorker.isRunning() && hasNextPage) {
pageNumber++;
requestData(true);
}
}
}
});
headerSubscriberButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, currentChannelInfo.feed_url);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(currentChannelInfo.feed_url));
startActivity(i);
}
});
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
private String buildSubscriberString(long count) {
String out = NumberFormat.getNumberInstance().format(count);
out += " " + getString(count > 1 ? R.string.subscriber_plural : R.string.subscriber);
return out;
}
private void requestData(boolean onlyVideos) {
if (currentExtractorWorker != null && currentExtractorWorker.isRunning()) currentExtractorWorker.cancel();
isLoading = true;
if (!onlyVideos) {
//delete already displayed content
loadingProgressBar.setVisibility(View.VISIBLE);
infoListAdapter.clearSteamItemList();
pageNumber = 0;
headerSubscriberLayout.setVisibility(View.GONE);
headerTitleView.setText(channelName != null ? channelName : "");
if (activity.getSupportActionBar() != null) activity.getSupportActionBar().setTitle(channelName != null ? channelName : "");
if (SDK_INT >= 21) {
headerChannelBanner.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.channel_banner));
headerAvatarView.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.buddy));
}
infoListAdapter.showFooter(false);
}
currentExtractorWorker = new ChannelExtractorWorker(activity, serviceId, channelUrl, pageNumber, this);
currentExtractorWorker.setOnlyVideos(onlyVideos);
currentExtractorWorker.start();
}
private void addVideos(ChannelInfo info) {
infoListAdapter.addInfoItemList(info.related_streams);
}
/*//////////////////////////////////////////////////////////////////////////
// OnChannelInfoReceiveListener
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onReceive(ChannelInfo info) {
if (info == null || isRemoving() || !isVisible()) return;
currentChannelInfo = info;
if (!currentExtractorWorker.isOnlyVideos()) {
headerRootLayout.setVisibility(View.VISIBLE);
loadingProgressBar.setVisibility(View.GONE);
if (info.channel_name != null && !info.channel_name.isEmpty()) {
if (activity.getSupportActionBar() != null) activity.getSupportActionBar().setTitle(info.channel_name);
headerTitleView.setText(info.channel_name);
channelName = info.channel_name;
} else channelName = "";
if (info.banner_url != null && !info.banner_url.isEmpty()) {
imageLoader.displayImage(info.banner_url, headerChannelBanner,
new ImageErrorLoadingListener(activity, rootView, info.service_id));
}
if (info.avatar_url != null && !info.avatar_url.isEmpty()) {
headerAvatarView.setVisibility(View.VISIBLE);
imageLoader.displayImage(info.avatar_url, headerAvatarView,
new ImageErrorLoadingListener(activity, rootView, info.service_id));
}
if (info.subscriberCount != -1) {
headerSubscriberView.setText(buildSubscriberString(info.subscriberCount));
}
if ((info.feed_url != null && !info.feed_url.isEmpty()) || (info.subscriberCount != -1)) {
headerSubscriberLayout.setVisibility(View.VISIBLE);
}
if (info.feed_url == null || info.feed_url.isEmpty()) {
headerSubscriberButton.setVisibility(View.INVISIBLE);
}
infoListAdapter.showFooter(true);
}
hasNextPage = info.hasNextPage;
if (!hasNextPage) infoListAdapter.showFooter(false);
addVideos(info);
isLoading = false;
}
@Override
public void onError(int messageId) {
Toast.makeText(activity, messageId, Toast.LENGTH_LONG).show();
}
@Override
public void onUnrecoverableError(Exception exception) {
activity.finish();
}
}

View File

@@ -1,6 +1,5 @@
package org.schabi.newpipe;
package org.schabi.newpipe.fragments.detail;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
@@ -11,8 +10,10 @@ import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.MediaFormat;
import org.schabi.newpipe.extractor.VideoInfo;
import org.schabi.newpipe.extractor.stream_info.VideoStream;
import org.schabi.newpipe.util.Utils;
import java.util.List;
@@ -43,17 +44,18 @@ class ActionBarHandler {
private AppCompatActivity activity;
private int selectedVideoStream = -1;
private SharedPreferences defaultPreferences = null;
private SharedPreferences defaultPreferences;
private Menu menu;
// Only callbacks are listed here, there are more actions which don't need a callback.
// those are edited directly. Typically VideoItemDetailFragment will implement those callbacks.
private OnActionListener onShareListener = null;
private OnActionListener onOpenInBrowserListener = null;
private OnActionListener onDownloadListener = null;
private OnActionListener onPlayWithKodiListener = null;
private OnActionListener onPlayAudioListener = null;
// those are edited directly. Typically VideoDetailFragment will implement those callbacks.
private OnActionListener onShareListener;
private OnActionListener onOpenInBrowserListener;
private OnActionListener onOpenInPopupListener;
private OnActionListener onDownloadListener;
private OnActionListener onPlayWithKodiListener;
private OnActionListener onPlayAudioListener;
// Triggered when a stream related action is triggered.
@@ -75,7 +77,7 @@ class ActionBarHandler {
}
}
public void setupStreamList(final List<VideoInfo.VideoStream> videoStreams) {
public void setupStreamList(final List<VideoStream> videoStreams) {
if (activity != null) {
selectedVideoStream = 0;
@@ -83,10 +85,10 @@ class ActionBarHandler {
// this array will be shown in the dropdown menu for selecting the stream/resolution.
String[] itemArray = new String[videoStreams.size()];
for (int i = 0; i < videoStreams.size(); i++) {
VideoInfo.VideoStream item = videoStreams.get(i);
VideoStream item = videoStreams.get(i);
itemArray[i] = MediaFormat.getNameById(item.format) + " " + item.resolution;
}
int defaultResolution = getDefaultResolution(videoStreams);
int defaultResolution = Utils.getDefaultResolution(activity, videoStreams);
ArrayAdapter<String> itemAdapter = new ArrayAdapter<>(activity.getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, itemArray);
@@ -107,23 +109,6 @@ class ActionBarHandler {
}
}
private int getDefaultResolution(final List<VideoInfo.VideoStream> videoStreams) {
String defaultResolution = defaultPreferences
.getString(activity.getString(R.string.default_resolution_key),
activity.getString(R.string.default_resolution_value));
for (int i = 0; i < videoStreams.size(); i++) {
VideoInfo.VideoStream item = videoStreams.get(i);
if (defaultResolution.equals(item.resolution)) {
return i;
}
}
// this is actually an error,
// but maybe there is really no stream fitting to the default value.
return 0;
}
public void setupMenu(Menu menu, MenuInflater inflater) {
this.menu = menu;
@@ -164,11 +149,6 @@ class ActionBarHandler {
onDownloadListener.onActionSelected(selectedVideoStream);
}
return true;
case R.id.action_settings: {
Intent intent = new Intent(activity, SettingsActivity.class);
activity.startActivity(intent);
return true;
}
case R.id.action_play_with_kodi:
if(onPlayWithKodiListener != null) {
onPlayWithKodiListener.onActionSelected(selectedVideoStream);
@@ -179,6 +159,12 @@ class ActionBarHandler {
onPlayAudioListener.onActionSelected(selectedVideoStream);
}
return true;
case R.id.menu_item_popup: {
if(onOpenInPopupListener != null) {
onOpenInPopupListener.onActionSelected(selectedVideoStream);
}
return true;
}
default:
Log.e(TAG, "Menu Item not known");
}
@@ -197,6 +183,10 @@ class ActionBarHandler {
onOpenInBrowserListener = listener;
}
public void setOnOpenInPopupListener(OnActionListener listener) {
onOpenInPopupListener = listener;
}
public void setOnDownloadListener(OnActionListener listener) {
onDownloadListener = listener;
}

View File

@@ -0,0 +1,31 @@
package org.schabi.newpipe.fragments.detail;
import java.io.Serializable;
@SuppressWarnings("WeakerAccess")
public class StackItem implements Serializable {
private String title, url;
public StackItem(String url, String title) {
this.title = title;
this.url = url;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
@Override
public String toString() {
return getUrl() + " > " + getTitle();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,440 @@
package org.schabi.newpipe.fragments.search;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.schabi.newpipe.R;
import org.schabi.newpipe.ReCaptchaActivity;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.extractor.search.SearchEngine;
import org.schabi.newpipe.extractor.search.SearchResult;
import org.schabi.newpipe.fragments.OnItemSelectedListener;
import org.schabi.newpipe.info_list.InfoItemBuilder;
import org.schabi.newpipe.info_list.InfoListAdapter;
import org.schabi.newpipe.report.ErrorActivity;
import org.schabi.newpipe.util.NavigationHelper;
import java.util.EnumSet;
import static android.app.Activity.RESULT_OK;
import static org.schabi.newpipe.ReCaptchaActivity.RECAPTCHA_REQUEST;
/**
* Created by Christian Schabesberger on 02.08.16.
* <p>
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* SearchFragment.java is part of NewPipe.
* <p>
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class SearchFragment extends Fragment implements SearchView.OnQueryTextListener, SearchWorker.SearchWorkerResultListener {
private static final String TAG = SearchFragment.class.toString();
// savedInstanceBundle arguments
private static final String QUERY = "query";
private static final String STREAMING_SERVICE = "streaming_service";
private int streamingServiceId = -1;
private String searchQuery = "";
private boolean isLoading = false;
@SuppressWarnings("FieldCanBeLocal")
private SearchView searchView;
private RecyclerView recyclerView;
private ProgressBar loadingIndicator;
private int pageNumber = 0;
private SuggestionListAdapter suggestionListAdapter;
private InfoListAdapter infoListAdapter;
private LinearLayoutManager streamInfoListLayoutManager;
private EnumSet<SearchEngine.Filter> filter = EnumSet.of(SearchEngine.Filter.CHANNEL, SearchEngine.Filter.STREAM);
private OnItemSelectedListener onItemSelectedListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public SearchFragment() {
}
@SuppressWarnings("unused")
public static SearchFragment newInstance(int streamingServiceId, String searchQuery) {
Bundle args = new Bundle();
args.putInt(STREAMING_SERVICE, streamingServiceId);
args.putString(QUERY, searchQuery);
SearchFragment fragment = new SearchFragment();
fragment.setArguments(args);
return fragment;
}
/*//////////////////////////////////////////////////////////////////////////
// Fragment's LifeCycle
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onAttach(Context context) {
super.onAttach(context);
onItemSelectedListener = ((OnItemSelectedListener) context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
searchQuery = "";
isLoading = false;
if (savedInstanceState != null) {
searchQuery = savedInstanceState.getString(QUERY);
streamingServiceId = savedInstanceState.getInt(STREAMING_SERVICE);
} else {
try {
Bundle args = getArguments();
if (args != null) {
searchQuery = args.getString(QUERY);
streamingServiceId = args.getInt(STREAMING_SERVICE);
} else {
streamingServiceId = NewPipe.getIdOfService("Youtube");
}
} catch (Exception e) {
e.printStackTrace();
ErrorActivity.reportError(getActivity(), e, null,
getActivity().findViewById(android.R.id.content),
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
NewPipe.getNameOfService(streamingServiceId),
"", R.string.general_error));
}
}
setHasOptionsMenu(true);
SearchWorker sw = SearchWorker.getInstance();
sw.setSearchWorkerResultListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
Context context = view.getContext();
loadingIndicator = (ProgressBar) view.findViewById(R.id.loading_progress_bar);
recyclerView = (RecyclerView) view.findViewById(R.id.list);
streamInfoListLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(streamInfoListLayoutManager);
infoListAdapter = new InfoListAdapter(getActivity(),
getActivity().findViewById(android.R.id.content));
infoListAdapter.setFooter(inflater.inflate(R.layout.pignate_footer, recyclerView, false));
infoListAdapter.showFooter(false);
infoListAdapter.setOnStreamInfoItemSelectedListener(new InfoItemBuilder.OnInfoItemSelectedListener() {
@Override
public void selected(int serviceId, String url, String title) {
NavigationHelper.openVideoDetail(onItemSelectedListener, serviceId, url, title);
}
});
infoListAdapter.setOnChannelInfoItemSelectedListener(new InfoItemBuilder.OnInfoItemSelectedListener() {
@Override
public void selected(int serviceId, String url, String title) {
NavigationHelper.openChannel(onItemSelectedListener, serviceId, url, title);
}
});
recyclerView.setAdapter(infoListAdapter);
recyclerView.clearOnScrollListeners();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int pastVisiblesItems, visibleItemCount, totalItemCount;
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) //check for scroll down
{
visibleItemCount = streamInfoListLayoutManager.getChildCount();
totalItemCount = streamInfoListLayoutManager.getItemCount();
pastVisiblesItems = streamInfoListLayoutManager.findFirstVisibleItemPosition();
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && !isLoading) {
pageNumber++;
recyclerView.post(new Runnable() {
@Override
public void run() {
infoListAdapter.showFooter(true);
}
});
search(searchQuery, pageNumber);
}
}
}
});
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (!searchQuery.isEmpty()) {
search(searchQuery);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
recyclerView.removeAllViews();
infoListAdapter.clearSteamItemList();
recyclerView = null;
}
@Override
public void onResume() {
super.onResume();
if (isLoading && !searchQuery.isEmpty()) {
search(searchQuery);
}
}
@Override
public void onStop() {
super.onStop();
SearchWorker.getInstance().terminate();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(QUERY, searchQuery);
outState.putInt(STREAMING_SERVICE, streamingServiceId);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RECAPTCHA_REQUEST:
if (resultCode == RESULT_OK && searchQuery.length() != 0) {
search(searchQuery);
} else Log.e(TAG, "ReCaptcha failed");
break;
default:
Log.e(TAG, "Request code from activity not supported [" + requestCode + "]");
break;
}
}
/*//////////////////////////////////////////////////////////////////////////
// Menu
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (supportActionBar != null) {
supportActionBar.setDisplayHomeAsUpEnabled(false);
supportActionBar.setDisplayShowTitleEnabled(false);
//noinspection deprecation
supportActionBar.setNavigationMode(0);
}
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
searchView = (SearchView) searchItem.getActionView();
setupSearchView(searchView);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_filter_all:
changeFilter(item, EnumSet.of(SearchEngine.Filter.STREAM, SearchEngine.Filter.CHANNEL));
return true;
case R.id.menu_filter_video:
changeFilter(item, EnumSet.of(SearchEngine.Filter.STREAM));
return true;
case R.id.menu_filter_channel:
changeFilter(item, EnumSet.of(SearchEngine.Filter.CHANNEL));
return true;
default:
return false;
}
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
private void changeFilter(MenuItem item, EnumSet<SearchEngine.Filter> filter) {
this.filter = filter;
item.setChecked(true);
if (searchQuery != null && !searchQuery.isEmpty()) {
Log.e(TAG, "Fuck+ " + searchQuery);
search(searchQuery);
}
}
private void setupSearchView(SearchView searchView) {
suggestionListAdapter = new SuggestionListAdapter(getActivity());
searchView.setSuggestionsAdapter(suggestionListAdapter);
searchView.setOnSuggestionListener(new SearchSuggestionListener(searchView, suggestionListAdapter));
searchView.setOnQueryTextListener(this);
if (searchQuery != null && !searchQuery.isEmpty()) {
searchView.setQuery(searchQuery, false);
searchView.setIconifiedByDefault(false);
}
}
private void search(String query) {
infoListAdapter.clearSteamItemList();
infoListAdapter.showFooter(false);
pageNumber = 0;
searchQuery = query;
search(query, pageNumber);
hideBackground();
loadingIndicator.setVisibility(View.VISIBLE);
}
private void search(String query, int page) {
isLoading = true;
SearchWorker sw = SearchWorker.getInstance();
sw.search(streamingServiceId,
query,
page,
getActivity(),
filter);
}
private void setDoneLoading() {
isLoading = false;
loadingIndicator.setVisibility(View.GONE);
infoListAdapter.showFooter(false);
}
/**
* Hides the "dummy" background when no results are shown
*/
private void hideBackground() {
View view = getView();
if (view == null) return;
view.findViewById(R.id.mainBG).setVisibility(View.GONE);
}
private void searchSuggestions(String query) {
SuggestionSearchRunnable suggestionSearchRunnable =
new SuggestionSearchRunnable(streamingServiceId, query, getActivity(), suggestionListAdapter);
Thread suggestionThread = new Thread(suggestionSearchRunnable);
suggestionThread.start();
}
public boolean isMainBgVisible() {
return getActivity().findViewById(R.id.mainBG).getVisibility() == View.VISIBLE;
}
/*//////////////////////////////////////////////////////////////////////////
// OnQueryTextListener
//////////////////////////////////////////////////////////////////////////*/
@Override
public boolean onQueryTextSubmit(String query) {
Activity a = getActivity();
try {
search(query);
// hide virtual keyboard
InputMethodManager inputManager =
(InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
try {
//noinspection ConstantConditions
inputManager.hideSoftInputFromWindow(
a.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (NullPointerException e) {
e.printStackTrace();
ErrorActivity.reportError(a, e, null,
a.findViewById(android.R.id.content),
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
NewPipe.getNameOfService(streamingServiceId),
"Could not get widget with focus", R.string.general_error));
}
// clear focus
// 1. to not open up the keyboard after switching back to this
// 2. It's a workaround to a seeming bug by the Android OS it self, causing
// onQueryTextSubmit to trigger twice when focus is not cleared.
// See: http://stackoverflow.com/questions/17874951/searchview-onquerytextsubmit-runs-twice-while-i-pressed-once
a.getCurrentFocus().clearFocus();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()) {
searchSuggestions(newText);
}
return true;
}
/*//////////////////////////////////////////////////////////////////////////
// SearchWorkerResultListener
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onResult(SearchResult result) {
infoListAdapter.addInfoItemList(result.resultList);
setDoneLoading();
}
@Override
public void onNothingFound(int stringResource) {
//setListShown(true);
Toast.makeText(getActivity(), getString(stringResource), Toast.LENGTH_SHORT).show();
setDoneLoading();
}
@Override
public void onError(String message) {
//setListShown(true);
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
setDoneLoading();
}
@Override
public void onReCaptchaChallenge() {
Toast.makeText(getActivity(), "ReCaptcha Challenge requested",
Toast.LENGTH_LONG).show();
// Starting ReCaptcha Challenge Activity
startActivityForResult(new Intent(getActivity(), ReCaptchaActivity.class), RECAPTCHA_REQUEST);
}
}

View File

@@ -0,0 +1,49 @@
package org.schabi.newpipe.fragments.search;
import android.support.v7.widget.SearchView;
/**
* Created by Christian Schabesberger on 02.08.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* SearchSuggestionListener.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class SearchSuggestionListener implements SearchView.OnSuggestionListener{
private final SearchView searchView;
private final SuggestionListAdapter adapter;
public SearchSuggestionListener(SearchView searchView, SuggestionListAdapter adapter) {
this.searchView = searchView;
this.adapter = adapter;
}
@Override
public boolean onSuggestionSelect(int position) {
String suggestion = adapter.getSuggestion(position);
searchView.setQuery(suggestion,true);
return false;
}
@Override
public boolean onSuggestionClick(int position) {
String suggestion = adapter.getSuggestion(position);
searchView.setQuery(suggestion,true);
return false;
}
}

View File

@@ -0,0 +1,216 @@
package org.schabi.newpipe.fragments.search;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.extractor.exceptions.ExtractionException;
import org.schabi.newpipe.extractor.exceptions.ReCaptchaException;
import org.schabi.newpipe.extractor.search.SearchEngine;
import org.schabi.newpipe.extractor.search.SearchResult;
import org.schabi.newpipe.report.ErrorActivity;
import java.io.IOException;
import java.util.EnumSet;
/**
* Created by Christian Schabesberger on 02.08.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* SearchWorker.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class SearchWorker {
private static final String TAG = SearchWorker.class.toString();
public interface SearchWorkerResultListener {
void onResult(SearchResult result);
void onNothingFound(final int stringResource);
void onError(String message);
void onReCaptchaChallenge();
}
private class ResultRunnable implements Runnable {
private final SearchResult result;
private int requestId = 0;
public ResultRunnable(SearchResult result, int requestId) {
this.result = result;
this.requestId = requestId;
}
@Override
public void run() {
if(this.requestId == SearchWorker.this.requestId) {
searchWorkerResultListener.onResult(result);
}
}
}
private class SearchRunnable implements Runnable {
public static final String YOUTUBE = "Youtube";
private final String query;
private final int page;
private final EnumSet<SearchEngine.Filter> filter;
final Handler h = new Handler();
private volatile boolean runs = true;
private Activity a = null;
private int serviceId = -1;
public SearchRunnable(int serviceId,
String query,
int page,
EnumSet<SearchEngine.Filter> filter,
Activity activity,
int requestId) {
this.serviceId = serviceId;
this.query = query;
this.page = page;
this.filter = filter;
this.a = activity;
}
void terminate() {
runs = false;
}
@Override
public void run() {
final String serviceName = NewPipe.getNameOfService(serviceId);
SearchResult result = null;
SearchEngine engine = null;
try {
engine = NewPipe.getService(serviceId)
.getSearchEngineInstance();
} catch(ExtractionException e) {
ErrorActivity.reportError(h, a, e, null, null,
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
Integer.toString(serviceId), query, R.string.general_error));
return;
}
try {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(a);
String searchLanguageKey = a.getString(R.string.search_language_key);
String searchLanguage = sp.getString(searchLanguageKey,
a.getString(R.string.default_language_value));
result = SearchResult
.getSearchResult(engine, query, page, searchLanguage, filter);
if(runs) {
h.post(new ResultRunnable(result, requestId));
}
// look for errors during extraction
// soft errors:
View rootView = a.findViewById(android.R.id.content);
if(result != null &&
!result.errors.isEmpty()) {
Log.e(TAG, "OCCURRED ERRORS DURING SEARCH EXTRACTION:");
for(Throwable e : result.errors) {
e.printStackTrace();
Log.e(TAG, "------");
}
if(result.resultList.isEmpty()&& !result.errors.isEmpty()) {
// if it compleatly failes dont show snackbar, instead show error directlry
ErrorActivity.reportError(h, a, result.errors, null, null,
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
serviceName, query, R.string.parsing_error));
} else {
// if it partly show snackbar
ErrorActivity.reportError(h, a, result.errors, null, rootView,
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
serviceName, query, R.string.light_parsing_error));
}
}
// hard errors:
} catch (ReCaptchaException e) {
h.post(new Runnable() {
@Override
public void run() {
searchWorkerResultListener.onReCaptchaChallenge();
}
});
} catch(IOException e) {
h.post(new Runnable() {
@Override
public void run() {
searchWorkerResultListener.onNothingFound(R.string.network_error);
}
});
e.printStackTrace();
} catch(final SearchEngine.NothingFoundException e) {
h.post(new Runnable() {
@Override
public void run() {
searchWorkerResultListener.onError(e.getMessage());
}
});
} catch(ExtractionException e) {
ErrorActivity.reportError(h, a, e, null, null,
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
serviceName, query, R.string.parsing_error));
//postNewErrorToast(h, R.string.parsing_error);
e.printStackTrace();
} catch(Exception e) {
ErrorActivity.reportError(h, a, e, null, null,
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
/* todo: this shoudl not be assigned static */ YOUTUBE, query, R.string.general_error));
e.printStackTrace();
}
}
}
private static SearchWorker searchWorker = null;
private SearchWorkerResultListener searchWorkerResultListener = null;
private SearchRunnable runnable = null;
private int requestId = 0; //prevents running requests that have already ben expired
public static SearchWorker getInstance() {
return searchWorker == null ? (searchWorker = new SearchWorker()) : searchWorker;
}
public void setSearchWorkerResultListener(SearchWorkerResultListener listener) {
searchWorkerResultListener = listener;
}
private SearchWorker() {
}
public void search(int serviceId,
String query,
int page,
Activity a,
EnumSet<SearchEngine.Filter> filter) {
if(runnable != null) {
terminate();
}
runnable = new SearchRunnable(serviceId, query, page, filter, a, requestId);
Thread thread = new Thread(runnable);
thread.start();
}
public void terminate() {
if (runnable == null) return;
requestId++;
runnable.terminate();
}
}

View File

@@ -0,0 +1,84 @@
package org.schabi.newpipe.fragments.search;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.support.v4.widget.ResourceCursorAdapter;
import android.view.View;
import android.widget.TextView;
import java.util.List;
/**
* Created by Christian Schabesberger on 02.08.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* SuggestionListAdapter.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* {@link ResourceCursorAdapter} to display suggestions.
*/
public class SuggestionListAdapter extends ResourceCursorAdapter {
private static final String[] columns = new String[]{"_id", "title"};
private static final int INDEX_ID = 0;
private static final int INDEX_TITLE = 1;
public SuggestionListAdapter(Context context) {
super(context, android.R.layout.simple_list_item_1, null, 0);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.suggestionTitle.setText(cursor.getString(INDEX_TITLE));
}
/**
* Update the suggestion list
* @param suggestions the list of suggestions
*/
public void updateAdapter(List<String> suggestions) {
MatrixCursor cursor = new MatrixCursor(columns, suggestions.size());
int i = 0;
for (String suggestion : suggestions) {
String[] columnValues = new String[columns.length];
columnValues[INDEX_TITLE] = suggestion;
columnValues[INDEX_ID] = Integer.toString(i);
cursor.addRow(columnValues);
i++;
}
changeCursor(cursor);
}
/**
* Get the suggestion for a position
* @param position the position of the suggestion
* @return the suggestion
*/
public String getSuggestion(int position) {
return ((Cursor) getItem(position)).getString(INDEX_TITLE);
}
private class ViewHolder {
private final TextView suggestionTitle;
private ViewHolder(View view) {
this.suggestionTitle = (TextView) view.findViewById(android.R.id.text1);
}
}
}

View File

@@ -0,0 +1,105 @@
package org.schabi.newpipe.fragments.search;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.widget.Toast;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.extractor.SuggestionExtractor;
import org.schabi.newpipe.extractor.exceptions.ExtractionException;
import org.schabi.newpipe.report.ErrorActivity;
import java.io.IOException;
import java.util.List;
/**
* Created by Christian Schabesberger on 02.08.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* SuggestionSearchRunnable.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class SuggestionSearchRunnable implements Runnable{
/**
* Runnable to update a {@link SuggestionListAdapter}
*/
private class SuggestionResultRunnable implements Runnable{
private final List<String> suggestions;
private SuggestionResultRunnable(List<String> suggestions) {
this.suggestions = suggestions;
}
@Override
public void run() {
adapter.updateAdapter(suggestions);
}
}
private final int serviceId;
private final String query;
private final Handler h = new Handler();
private final Activity a;
private final SuggestionListAdapter adapter;
public SuggestionSearchRunnable(int serviceId, String query,
Activity activity, SuggestionListAdapter adapter) {
this.serviceId = serviceId;
this.query = query;
this.a = activity;
this.adapter = adapter;
}
@Override
public void run() {
try {
SuggestionExtractor se =
NewPipe.getService(serviceId).getSuggestionExtractorInstance();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(a);
String searchLanguageKey = a.getString(R.string.search_language_key);
String searchLanguage = sp.getString(searchLanguageKey,
a.getString(R.string.default_language_value));
List<String> suggestions = se.suggestionList(query, searchLanguage);
h.post(new SuggestionResultRunnable(suggestions));
} catch (ExtractionException e) {
ErrorActivity.reportError(h, a, e, null, a.findViewById(android.R.id.content),
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
NewPipe.getNameOfService(serviceId), query, R.string.parsing_error));
e.printStackTrace();
} catch (IOException e) {
postNewErrorToast(h, R.string.network_error);
e.printStackTrace();
} catch (Exception e) {
ErrorActivity.reportError(h, a, e, null, a.findViewById(android.R.id.content),
ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
NewPipe.getNameOfService(serviceId), query, R.string.general_error));
}
}
private void postNewErrorToast(Handler h, final int stringResource) {
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(a, a.getString(stringResource),
Toast.LENGTH_SHORT).show();
}
});
}
}

View File

@@ -0,0 +1,54 @@
package org.schabi.newpipe.info_list;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.InfoItem;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by Christian Schabesberger on 12.02.17.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* ChannelInfoItemHolder .java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class ChannelInfoItemHolder extends InfoItemHolder {
public final CircleImageView itemThumbnailView;
public final TextView itemChannelTitleView;
public final TextView itemSubscriberCountView;
public final TextView itemVideoCountView;
public final TextView itemChannelDescriptionView;
public final Button itemButton;
ChannelInfoItemHolder(View v) {
super(v);
itemThumbnailView = (CircleImageView) v.findViewById(R.id.itemThumbnailView);
itemChannelTitleView = (TextView) v.findViewById(R.id.itemChannelTitleView);
itemSubscriberCountView = (TextView) v.findViewById(R.id.itemSubscriberCountView);
itemVideoCountView = (TextView) v.findViewById(R.id.itemVideoCountView);
itemChannelDescriptionView = (TextView) v.findViewById(R.id.itemChannelDescriptionView);
itemButton = (Button) v.findViewById(R.id.item_button);
}
@Override
public InfoItem.InfoType infoType() {
return InfoItem.InfoType.CHANNEL;
}
}

View File

@@ -0,0 +1,273 @@
package org.schabi.newpipe.info_list;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.schabi.newpipe.ImageErrorLoadingListener;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.AbstractStreamInfo;
import org.schabi.newpipe.extractor.InfoItem;
import org.schabi.newpipe.extractor.channel.ChannelInfoItem;
import org.schabi.newpipe.extractor.stream_info.StreamInfoItem;
/**
* Created by Christian Schabesberger on 26.09.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* InfoItemBuilder.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class InfoItemBuilder {
private final String viewsS;
private final String videosS;
private final String subsS;
private final String subsPluralS;
private final String thousand;
private final String million;
private final String billion;
private static final String TAG = InfoItemBuilder.class.toString();
public interface OnInfoItemSelectedListener {
void selected(int serviceId, String url, String title);
}
private Context mContext = null;
private View rootView = null;
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions displayImageOptions =
new DisplayImageOptions.Builder().cacheInMemory(true).build();
private OnInfoItemSelectedListener onStreamInfoItemSelectedListener;
private OnInfoItemSelectedListener onChannelInfoItemSelectedListener;
public InfoItemBuilder(Context context, View rootView) {
mContext = context;
this.rootView = rootView;
viewsS = context.getString(R.string.views);
videosS = context.getString(R.string.videos);
subsS = context.getString(R.string.subscriber);
subsPluralS = context.getString(R.string.subscriber_plural);
thousand = context.getString(R.string.short_thousand);
million = context.getString(R.string.short_million);
billion = context.getString(R.string.short_billion);
}
public void setOnStreamInfoItemSelectedListener(
OnInfoItemSelectedListener listener) {
this.onStreamInfoItemSelectedListener = listener;
}
public void setOnChannelInfoItemSelectedListener(
OnInfoItemSelectedListener listener) {
this.onChannelInfoItemSelectedListener = listener;
}
public void buildByHolder(InfoItemHolder holder, final InfoItem i) {
if(i.infoType() != holder.infoType())
return;
switch(i.infoType()) {
case STREAM:
buildStreamInfoItem((StreamInfoItemHolder) holder, (StreamInfoItem) i);
break;
case CHANNEL:
buildChannelInfoItem((ChannelInfoItemHolder) holder, (ChannelInfoItem) i);
break;
case PLAYLIST:
Log.e(TAG, "Not yet implemented");
break;
default:
Log.e(TAG, "Trollolo");
}
}
public View buildView(ViewGroup parent, final InfoItem info) {
View itemView = null;
InfoItemHolder holder = null;
switch(info.infoType()) {
case STREAM:
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.stream_item, parent, false);
holder = new StreamInfoItemHolder(itemView);
break;
case CHANNEL:
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.channel_item, parent, false);
holder = new ChannelInfoItemHolder(itemView);
break;
case PLAYLIST:
Log.e(TAG, "Not yet implemented");
default:
Log.e(TAG, "Trollolo");
}
buildByHolder(holder, info);
return itemView;
}
private void buildStreamInfoItem(StreamInfoItemHolder holder, final StreamInfoItem info) {
if(info.infoType() != InfoItem.InfoType.STREAM) {
Log.e("InfoItemBuilder", "Info type not yet supported");
}
// fill holder with information
holder.itemVideoTitleView.setText(info.title);
if(info.uploader != null && !info.uploader.isEmpty()) {
holder.itemUploaderView.setText(info.uploader);
} else {
holder.itemUploaderView.setVisibility(View.INVISIBLE);
}
if(info.duration > 0) {
holder.itemDurationView.setText(getDurationString(info.duration));
} else {
if(info.stream_type == AbstractStreamInfo.StreamType.LIVE_STREAM) {
holder.itemDurationView.setText(R.string.duration_live);
} else {
holder.itemDurationView.setVisibility(View.GONE);
}
}
if(info.view_count >= 0) {
holder.itemViewCountView.setText(shortViewCount(info.view_count));
} else {
holder.itemViewCountView.setVisibility(View.GONE);
}
if(info.upload_date != null && !info.upload_date.isEmpty()) {
holder.itemUploadDateView.setText(info.upload_date + "");
}
holder.itemThumbnailView.setImageResource(R.drawable.dummy_thumbnail);
if(info.thumbnail_url != null && !info.thumbnail_url.isEmpty()) {
imageLoader.displayImage(info.thumbnail_url,
holder.itemThumbnailView,
displayImageOptions,
new ImageErrorLoadingListener(mContext, rootView, info.service_id));
}
holder.itemButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onStreamInfoItemSelectedListener.selected(info.service_id, info.webpage_url, info.getTitle());
}
});
}
private void buildChannelInfoItem(ChannelInfoItemHolder holder, final ChannelInfoItem info) {
holder.itemChannelTitleView.setText(info.getTitle());
holder.itemSubscriberCountView.setText(shortSubscriber(info.subscriberCount) + "");
holder.itemVideoCountView.setText(info.videoAmount + " " + videosS);
holder.itemChannelDescriptionView.setText(info.description);
holder.itemThumbnailView.setImageResource(R.drawable.buddy_channel_item);
if(info.thumbnailUrl != null && !info.thumbnailUrl.isEmpty()) {
imageLoader.displayImage(info.thumbnailUrl,
holder.itemThumbnailView,
displayImageOptions,
new ImageErrorLoadingListener(mContext, rootView, info.serviceId));
}
holder.itemButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onChannelInfoItemSelectedListener.selected(info.serviceId, info.getLink(), info.channelName);
}
});
}
public String shortViewCount(Long viewCount){
if(viewCount >= 1000000000){
return Long.toString(viewCount/1000000000)+ billion + " " + viewsS;
}else if(viewCount>=1000000){
return Long.toString(viewCount/1000000)+ million + " " + viewsS;
}else if(viewCount>=1000){
return Long.toString(viewCount/1000)+ thousand + " " + viewsS;
}else {
return Long.toString(viewCount)+ " " + viewsS;
}
}
public String shortSubscriber(Long count) {
String curSubString = count > 1 ? subsPluralS : subsS;
if (count >= 1000000000) {
return Long.toString(count / 1000000000) + billion + " " + curSubString;
} else if (count >= 1000000) {
return Long.toString(count / 1000000) + million + " " + curSubString;
} else if (count >= 1000) {
return Long.toString(count / 1000) + thousand + " " + curSubString;
} else {
return Long.toString(count) + " " + curSubString;
}
}
public static String getDurationString(int duration) {
String output = "";
int days = duration / (24 * 60 * 60); /* greater than a day */
duration %= (24 * 60 * 60);
int hours = duration / (60 * 60); /* greater than an hour */
duration %= (60 * 60);
int minutes = duration / 60;
int seconds = duration % 60;
//handle days
if(days > 0) {
output = Integer.toString(days) + ":";
}
// handle hours
if(hours > 0 || !output.isEmpty()) {
if(hours > 0) {
if(hours >= 10 || output.isEmpty()) {
output += Integer.toString(hours);
} else {
output += "0" + Integer.toString(hours);
}
} else {
output += "00";
}
output += ":";
}
//handle minutes
if(minutes > 0 || !output.isEmpty()) {
if(minutes > 0) {
if(minutes >= 10 || output.isEmpty()) {
output += Integer.toString(minutes);
} else {
output += "0" + Integer.toString(minutes);
}
} else {
output += "00";
}
output += ":";
}
//handle seconds
if(output.isEmpty()) {
output += "0:";
}
if(seconds >= 10) {
output += Integer.toString(seconds);
} else {
output += "0" + Integer.toString(seconds);
}
return output;
}
}

View File

@@ -1,10 +1,15 @@
package org.schabi.newpipe.extractor;
package org.schabi.newpipe.info_list;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import org.schabi.newpipe.extractor.InfoItem;
/**
* Created by Christian Schabesberger on 31.01.16.
* Created by Christian Schabesberger on 12.02.17.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* ParsingException.java is part of NewPipe.
* InfoItemHolder.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,16 +25,9 @@ package org.schabi.newpipe.extractor;
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class ParsingException extends ExctractionException {
public ParsingException() {}
public ParsingException(String message) {
super(message);
public abstract class InfoItemHolder extends RecyclerView.ViewHolder {
public InfoItemHolder(View v) {
super(v);
}
public ParsingException(Throwable cause) {
super(cause);
}
public ParsingException(String message, Throwable cause) {
super(message, cause);
}
}
public abstract InfoItem.InfoType infoType();
}

View File

@@ -0,0 +1,163 @@
package org.schabi.newpipe.info_list;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.InfoItem;
import java.util.List;
import java.util.Vector;
/**
* Created by Christian Schabesberger on 01.08.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* InfoListAdapter.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class InfoListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = InfoListAdapter.class.toString();
private final InfoItemBuilder infoItemBuilder;
private final List<InfoItem> infoItemList;
private boolean showFooter = false;
private View header = null;
private View footer = null;
public class HFHolder extends RecyclerView.ViewHolder {
public HFHolder(View v) {
super(v);
view = v;
}
public View view;
}
public void showFooter(boolean show) {
showFooter = show;
notifyDataSetChanged();
}
public InfoListAdapter(Activity a, View rootView) {
infoItemBuilder = new InfoItemBuilder(a, rootView);
infoItemList = new Vector<>();
}
public void setOnStreamInfoItemSelectedListener
(InfoItemBuilder.OnInfoItemSelectedListener listener) {
infoItemBuilder.setOnStreamInfoItemSelectedListener(listener);
}
public void setOnChannelInfoItemSelectedListener
(InfoItemBuilder.OnInfoItemSelectedListener listener) {
infoItemBuilder.setOnChannelInfoItemSelectedListener(listener);
}
public void addInfoItemList(List<InfoItem> data) {
if(data != null) {
infoItemList.addAll(data);
notifyDataSetChanged();
}
}
public void clearSteamItemList() {
infoItemList.clear();
notifyDataSetChanged();
}
public void setHeader(View header) {
this.header = header;
notifyDataSetChanged();
}
public void setFooter(View view) {
this.footer = view;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
int cound = infoItemList.size();
if(header != null) cound++;
if(footer != null && showFooter) cound++;
return cound;
}
// don't ask why we have to do that this way... it's android accept it -.-
@Override
public int getItemViewType(int position) {
if(header != null && position == 0) {
return 0;
} else if(header != null) {
position--;
}
if(footer != null && position == infoItemList.size() && showFooter) {
return 1;
}
switch(infoItemList.get(position).infoType()) {
case STREAM:
return 2;
case CHANNEL:
return 3;
case PLAYLIST:
return 4;
default:
Log.e(TAG, "Trollolo");
return -1;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
switch(type) {
case 0:
return new HFHolder(header);
case 1:
return new HFHolder(footer);
case 2:
return new StreamInfoItemHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.stream_item, parent, false));
case 3:
return new ChannelInfoItemHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.channel_item, parent, false));
case 4:
Log.e(TAG, "Playlist is not yet implemented");
return null;
default:
Log.e(TAG, "Trollolo");
return null;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {
//god damen f*** ANDROID SH**
if(holder instanceof InfoItemHolder) {
if(header != null) {
i--;
}
infoItemBuilder.buildByHolder((InfoItemHolder) holder, infoItemList.get(i));
} else if(holder instanceof HFHolder && i == 0 && header != null) {
((HFHolder) holder).view = header;
} else if(holder instanceof HFHolder && i == infoItemList.size() && footer != null && showFooter) {
((HFHolder) holder).view = footer;
}
}
}

View File

@@ -0,0 +1,58 @@
package org.schabi.newpipe.info_list;
import android.icu.text.IDNA;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.InfoItem;
/**
* Created by Christian Schabesberger on 01.08.16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* StreamInfoItemHolder.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class StreamInfoItemHolder extends InfoItemHolder {
public final ImageView itemThumbnailView;
public final TextView itemVideoTitleView,
itemUploaderView,
itemDurationView,
itemUploadDateView,
itemViewCountView;
public final Button itemButton;
public StreamInfoItemHolder(View v) {
super(v);
itemThumbnailView = (ImageView) v.findViewById(R.id.itemThumbnailView);
itemVideoTitleView = (TextView) v.findViewById(R.id.itemVideoTitleView);
itemUploaderView = (TextView) v.findViewById(R.id.itemUploaderView);
itemDurationView = (TextView) v.findViewById(R.id.itemDurationView);
itemUploadDateView = (TextView) v.findViewById(R.id.itemUploadDateView);
itemViewCountView = (TextView) v.findViewById(R.id.itemViewCountView);
itemButton = (Button) v.findViewById(R.id.item_button);
}
@Override
public InfoItem.InfoType infoType() {
return InfoItem.InfoType.STREAM;
}
}

View File

@@ -0,0 +1,455 @@
package org.schabi.newpipe.player;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.IntRange;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import org.schabi.newpipe.BuildConfig;
import org.schabi.newpipe.MainActivity;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.MediaFormat;
import org.schabi.newpipe.extractor.StreamingService;
import org.schabi.newpipe.extractor.stream_info.AudioStream;
import org.schabi.newpipe.util.Constants;
import org.schabi.newpipe.util.ThemeHelper;
import java.io.Serializable;
/**
* Base players joining the common properties
*
* @author mauriciocolli
*/
public class BackgroundPlayer extends Service {
private static final String TAG = "BackgroundPlayer";
private static final boolean DEBUG = BasePlayer.DEBUG;
public static final String ACTION_CLOSE = "org.schabi.newpipe.player.BackgroundPlayer.CLOSE";
public static final String ACTION_PLAY_PAUSE = "org.schabi.newpipe.player.BackgroundPlayer.PLAY_PAUSE";
public static final String ACTION_OPEN_DETAIL = "org.schabi.newpipe.player.BackgroundPlayer.OPEN_DETAIL";
public static final String ACTION_REPEAT = "org.schabi.newpipe.player.BackgroundPlayer.REPEAT";
public static final String ACTION_FAST_REWIND = "org.schabi.newpipe.player.BackgroundPlayer.ACTION_FAST_REWIND";
public static final String ACTION_FAST_FORWARD = "org.schabi.newpipe.player.BackgroundPlayer.ACTION_FAST_FORWARD";
public static final String AUDIO_STREAM = "video_only_audio_stream";
private AudioStream audioStream;
private BasePlayerImpl basePlayerImpl;
private PowerManager powerManager;
private WifiManager wifiManager;
private PowerManager.WakeLock wakeLock;
private WifiManager.WifiLock wifiLock;
/*//////////////////////////////////////////////////////////////////////////
// Notification
//////////////////////////////////////////////////////////////////////////*/
private static final int NOTIFICATION_ID = 123789;
private NotificationManager notificationManager;
private NotificationCompat.Builder notBuilder;
private RemoteViews notRemoteView;
private RemoteViews bigNotRemoteView;
private final String setAlphaMethodName = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) ? "setImageAlpha" : "setAlpha";
/*//////////////////////////////////////////////////////////////////////////
// Service's LifeCycle
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onCreate() {
if (DEBUG) Log.d(TAG, "onCreate() called");
notificationManager = ((NotificationManager) getSystemService(NOTIFICATION_SERVICE));
powerManager = ((PowerManager) getSystemService(POWER_SERVICE));
wifiManager = ((WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE));
ThemeHelper.setTheme(this, false);
basePlayerImpl = new BasePlayerImpl(this);
basePlayerImpl.setup();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (DEBUG) Log.d(TAG, "onStartCommand() called with: intent = [" + intent + "], flags = [" + flags + "], startId = [" + startId + "]");
basePlayerImpl.handleIntent(intent);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
if (DEBUG) Log.d(TAG, "destroy() called");
releaseWifiAndCpu();
stopForeground(true);
if (basePlayerImpl != null) basePlayerImpl.destroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*//////////////////////////////////////////////////////////////////////////
// Actions
//////////////////////////////////////////////////////////////////////////*/
public void onOpenDetail(Context context, String videoUrl, String videoTitle) {
if (DEBUG) Log.d(TAG, "onOpenDetail() called with: context = [" + context + "], videoUrl = [" + videoUrl + "]");
Intent i = new Intent(context, MainActivity.class);
i.putExtra(Constants.KEY_SERVICE_ID, 0);
i.putExtra(Constants.KEY_URL, videoUrl);
i.putExtra(Constants.KEY_TITLE, videoTitle);
i.putExtra(Constants.KEY_LINK_TYPE, StreamingService.LinkType.STREAM);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
private void onClose() {
if (basePlayerImpl != null) basePlayerImpl.destroyPlayer();
stopForeground(true);
releaseWifiAndCpu();
stopSelf();
}
private void onScreenOnOff(boolean on) {
if (DEBUG) Log.d(TAG, "onScreenOnOff() called with: on = [" + on + "]");
if (on) {
if (basePlayerImpl.isPlaying() && !basePlayerImpl.isProgressLoopRunning.get()) basePlayerImpl.startProgressLoop();
} else basePlayerImpl.stopProgressLoop();
}
/*//////////////////////////////////////////////////////////////////////////
// Notification
//////////////////////////////////////////////////////////////////////////*/
private NotificationCompat.Builder createNotification() {
notRemoteView = new RemoteViews(BuildConfig.APPLICATION_ID, R.layout.player_notification);
bigNotRemoteView = new RemoteViews(BuildConfig.APPLICATION_ID, R.layout.player_notification_expanded);
setupNotification(notRemoteView);
setupNotification(bigNotRemoteView);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_play_circle_filled_white_24dp)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setCustomContentView(notRemoteView)
.setCustomBigContentView(bigNotRemoteView);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) builder.setPriority(Notification.PRIORITY_MAX);
return builder;
}
private void setupNotification(RemoteViews remoteViews) {
//if (videoThumbnail != null) remoteViews.setImageViewBitmap(R.id.notificationCover, videoThumbnail);
///else remoteViews.setImageViewResource(R.id.notificationCover, R.drawable.dummy_thumbnail);
remoteViews.setTextViewText(R.id.notificationSongName, basePlayerImpl.getVideoTitle());
remoteViews.setTextViewText(R.id.notificationArtist, basePlayerImpl.getChannelName());
remoteViews.setOnClickPendingIntent(R.id.notificationPlayPause,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_PLAY_PAUSE), PendingIntent.FLAG_UPDATE_CURRENT));
remoteViews.setOnClickPendingIntent(R.id.notificationStop,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_CLOSE), PendingIntent.FLAG_UPDATE_CURRENT));
remoteViews.setOnClickPendingIntent(R.id.notificationContent,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_OPEN_DETAIL), PendingIntent.FLAG_UPDATE_CURRENT));
remoteViews.setOnClickPendingIntent(R.id.notificationRepeat,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_REPEAT), PendingIntent.FLAG_UPDATE_CURRENT));
remoteViews.setOnClickPendingIntent(R.id.notificationFRewind,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_FAST_REWIND), PendingIntent.FLAG_UPDATE_CURRENT));
remoteViews.setOnClickPendingIntent(R.id.notificationFForward,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_FAST_FORWARD), PendingIntent.FLAG_UPDATE_CURRENT));
switch (basePlayerImpl.getCurrentRepeatMode()) {
case REPEAT_DISABLED:
remoteViews.setInt(R.id.notificationRepeat, setAlphaMethodName, 77);
break;
case REPEAT_ONE:
remoteViews.setInt(R.id.notificationRepeat, setAlphaMethodName, 255);
break;
case REPEAT_ALL:
// Waiting :)
break;
}
}
/**
* Updates the notification, and the play/pause button in it.
* Used for changes on the remoteView
*
* @param drawableId if != -1, sets the drawable with that id on the play/pause button
*/
private void updateNotification(int drawableId) {
if (DEBUG) Log.d(TAG, "updateNotification() called with: drawableId = [" + drawableId + "]");
if (notBuilder == null) return;
if (drawableId != -1) {
if (notRemoteView != null) notRemoteView.setImageViewResource(R.id.notificationPlayPause, drawableId);
if (bigNotRemoteView != null) bigNotRemoteView.setImageViewResource(R.id.notificationPlayPause, drawableId);
}
notificationManager.notify(NOTIFICATION_ID, notBuilder.build());
}
private void setControlsOpacity(@IntRange(from = 0, to = 255) int opacity) {
if (notRemoteView != null) notRemoteView.setInt(R.id.notificationPlayPause, setAlphaMethodName, opacity);
if (bigNotRemoteView != null) bigNotRemoteView.setInt(R.id.notificationPlayPause, setAlphaMethodName, opacity);
if (notRemoteView != null) notRemoteView.setInt(R.id.notificationFForward, setAlphaMethodName, opacity);
if (bigNotRemoteView != null) bigNotRemoteView.setInt(R.id.notificationFForward, setAlphaMethodName, opacity);
if (notRemoteView != null) notRemoteView.setInt(R.id.notificationFRewind, setAlphaMethodName, opacity);
if (bigNotRemoteView != null) bigNotRemoteView.setInt(R.id.notificationFRewind, setAlphaMethodName, opacity);
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
private void lockWifiAndCpu() {
if (DEBUG) Log.d(TAG, "lockWifiAndCpu() called");
if (wakeLock != null && wakeLock.isHeld() && wifiLock != null && wifiLock.isHeld()) return;
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG);
if (wakeLock != null) wakeLock.acquire();
if (wifiLock != null) wifiLock.acquire();
}
private void releaseWifiAndCpu() {
if (DEBUG) Log.d(TAG, "releaseWifiAndCpu() called");
if (wakeLock != null && wakeLock.isHeld()) wakeLock.release();
if (wifiLock != null && wifiLock.isHeld()) wifiLock.release();
wakeLock = null;
wifiLock = null;
}
//////////////////////////////////////////////////////////////////////////
private class BasePlayerImpl extends BasePlayer {
BasePlayerImpl(Context context) {
super(context);
}
@Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
Serializable serializable = intent.getSerializableExtra(BackgroundPlayer.AUDIO_STREAM);
if (serializable instanceof AudioStream) audioStream = (AudioStream) serializable;
playUrl(audioStream.url, MediaFormat.getSuffixById(audioStream.format), true);
if (bigNotRemoteView != null) bigNotRemoteView.setProgressBar(R.id.notificationProgressBar, 100, 0, false);
if (notRemoteView != null) notRemoteView.setProgressBar(R.id.notificationProgressBar, 100, 0, false);
}
@Override
public void initThumbnail() {
if (notRemoteView != null) notRemoteView.setImageViewResource(R.id.notificationCover, R.drawable.dummy_thumbnail);
if (bigNotRemoteView != null) bigNotRemoteView.setImageViewResource(R.id.notificationCover, R.drawable.dummy_thumbnail);
updateNotification(-1);
super.initThumbnail();
}
@Override
public void onThumbnailReceived(Bitmap thumbnail) {
super.onThumbnailReceived(thumbnail);
if (thumbnail != null) {
if (notRemoteView != null) notRemoteView.setImageViewBitmap(R.id.notificationCover, thumbnail);
if (bigNotRemoteView != null) bigNotRemoteView.setImageViewBitmap(R.id.notificationCover, thumbnail);
updateNotification(-1);
}
}
@Override
public void playUrl(String url, String format, boolean autoPlay) {
super.playUrl(url, format, autoPlay);
notBuilder = createNotification();
startForeground(NOTIFICATION_ID, notBuilder.build());
}
@Override
public void onPrepared(boolean playWhenReady) {
super.onPrepared(playWhenReady);
if (simpleExoPlayer.getDuration() < 15000) {
PROGRESS_LOOP_INTERVAL = 1000;
FAST_FORWARD_REWIND_AMOUNT = 2000;
} else if (simpleExoPlayer.getDuration() > 60 * 60 * 1000) {
PROGRESS_LOOP_INTERVAL = 2000;
FAST_FORWARD_REWIND_AMOUNT = 60000;
} else {
PROGRESS_LOOP_INTERVAL = 2000;
FAST_FORWARD_REWIND_AMOUNT = 10000;
}
basePlayerImpl.getPlayer().setVolume(1f);
}
@Override
public void onRepeatClicked() {
super.onRepeatClicked();
int opacity = 255;
switch (currentRepeatMode) {
case REPEAT_DISABLED:
opacity = 77;
break;
case REPEAT_ONE:
opacity = 255;
break;
case REPEAT_ALL:
// Waiting :)
break;
}
if (notRemoteView != null) notRemoteView.setInt(R.id.notificationRepeat, setAlphaMethodName, opacity);
if (bigNotRemoteView != null) bigNotRemoteView.setInt(R.id.notificationRepeat, setAlphaMethodName, opacity);
updateNotification(-1);
}
@Override
public void onUpdateProgress(int currentProgress, int duration, int bufferPercent) {
if (bigNotRemoteView != null) bigNotRemoteView.setProgressBar(R.id.notificationProgressBar, duration, currentProgress, false);
if (notRemoteView != null) notRemoteView.setProgressBar(R.id.notificationProgressBar, duration, currentProgress, false);
updateNotification(-1);
}
@Override
public void onFastRewind() {
super.onFastRewind();
triggerProgressUpdate();
}
@Override
public void onFastForward() {
super.onFastForward();
triggerProgressUpdate();
}
@Override
public void onLoadingChanged(boolean isLoading) {
// Disable default behavior
}
@Override
public void destroy() {
super.destroy();
if (notRemoteView != null) notRemoteView.setImageViewBitmap(R.id.notificationCover, null);
if (bigNotRemoteView != null) bigNotRemoteView.setImageViewBitmap(R.id.notificationCover, null);
}
@Override
public void onError(Exception exception) {
exception.printStackTrace();
stopSelf();
}
/*//////////////////////////////////////////////////////////////////////////
// Broadcast Receiver
//////////////////////////////////////////////////////////////////////////*/
@Override
protected void setupBroadcastReceiver(IntentFilter intentFilter) {
super.setupBroadcastReceiver(intentFilter);
intentFilter.addAction(ACTION_CLOSE);
intentFilter.addAction(ACTION_PLAY_PAUSE);
intentFilter.addAction(ACTION_OPEN_DETAIL);
intentFilter.addAction(ACTION_REPEAT);
intentFilter.addAction(ACTION_FAST_FORWARD);
intentFilter.addAction(ACTION_FAST_REWIND);
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
}
@Override
public void onBroadcastReceived(Intent intent) {
super.onBroadcastReceived(intent);
if (DEBUG) Log.d(TAG, "onBroadcastReceived() called with: intent = [" + intent + "]");
switch (intent.getAction()) {
case ACTION_CLOSE:
onClose();
break;
case ACTION_PLAY_PAUSE:
onVideoPlayPause();
break;
case ACTION_OPEN_DETAIL:
onOpenDetail(BackgroundPlayer.this, basePlayerImpl.getVideoUrl(), basePlayerImpl.getVideoTitle());
break;
case ACTION_REPEAT:
onRepeatClicked();
break;
case ACTION_FAST_REWIND:
onFastRewind();
break;
case ACTION_FAST_FORWARD:
onFastForward();
break;
case Intent.ACTION_SCREEN_ON:
onScreenOnOff(true);
break;
case Intent.ACTION_SCREEN_OFF:
onScreenOnOff(false);
break;
}
}
/*//////////////////////////////////////////////////////////////////////////
// States
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onLoading() {
super.onLoading();
setControlsOpacity(77);
updateNotification(-1);
}
@Override
public void onPlaying() {
super.onPlaying();
setControlsOpacity(255);
updateNotification(R.drawable.ic_pause_white);
lockWifiAndCpu();
}
@Override
public void onPaused() {
super.onPaused();
updateNotification(R.drawable.ic_play_arrow_white);
if (isProgressLoopRunning.get()) stopProgressLoop();
releaseWifiAndCpu();
}
@Override
public void onCompleted() {
super.onCompleted();
setControlsOpacity(255);
if (bigNotRemoteView != null) bigNotRemoteView.setProgressBar(R.id.notificationProgressBar, 100, 100, false);
if (notRemoteView != null) notRemoteView.setProgressBar(R.id.notificationProgressBar, 100, 100, false);
updateNotification(R.drawable.ic_replay_white);
releaseWifiAndCpu();
}
}
}

View File

@@ -0,0 +1,717 @@
package org.schabi.newpipe.player;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import java.io.File;
import java.util.Formatter;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Base for the players, joining the common properties
*
* @author mauriciocolli
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public abstract class BasePlayer implements ExoPlayer.EventListener, AudioManager.OnAudioFocusChangeListener {
public static final boolean DEBUG = false;
public static final String TAG = "BasePlayer";
protected Context context;
protected SharedPreferences sharedPreferences;
protected AudioManager audioManager;
protected BroadcastReceiver broadcastReceiver;
protected IntentFilter intentFilter;
/*//////////////////////////////////////////////////////////////////////////
// Intent
//////////////////////////////////////////////////////////////////////////*/
public static final String VIDEO_URL = "video_url";
public static final String VIDEO_TITLE = "video_title";
public static final String VIDEO_THUMBNAIL_URL = "video_thumbnail_url";
public static final String START_POSITION = "start_position";
public static final String CHANNEL_NAME = "channel_name";
protected Bitmap videoThumbnail = null;
protected String videoUrl = "";
protected String videoTitle = "";
protected String videoThumbnailUrl = "";
protected int videoStartPos = -1;
protected String channelName = "";
/*//////////////////////////////////////////////////////////////////////////
// Player
//////////////////////////////////////////////////////////////////////////*/
public int FAST_FORWARD_REWIND_AMOUNT = 10000; // 10 Seconds
public static final String CACHE_FOLDER_NAME = "exoplayer";
protected SimpleExoPlayer simpleExoPlayer;
protected boolean isPrepared = false;
protected MediaSource mediaSource;
protected CacheDataSourceFactory cacheDataSourceFactory;
protected final DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
protected final DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
protected int PROGRESS_LOOP_INTERVAL = 100;
protected AtomicBoolean isProgressLoopRunning = new AtomicBoolean();
protected Handler progressLoop;
protected Runnable progressUpdate;
//////////////////////////////////////////////////////////////////////////*/
public BasePlayer(Context context) {
this.context = context;
this.progressLoop = new Handler();
this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
this.audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));
this.broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
onBroadcastReceived(intent);
}
};
this.intentFilter = new IntentFilter();
setupBroadcastReceiver(intentFilter);
context.registerReceiver(broadcastReceiver, intentFilter);
}
public void setup() {
if (simpleExoPlayer == null) initPlayer();
initListeners();
}
private void initExoPlayerCache() {
if (cacheDataSourceFactory == null) {
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, context.getPackageName()), bandwidthMeter);
File cacheDir = new File(context.getExternalCacheDir(), CACHE_FOLDER_NAME);
if (!cacheDir.exists()) {
//noinspection ResultOfMethodCallIgnored
cacheDir.mkdir();
}
if (DEBUG) Log.d(TAG, "initExoPlayerCache: cacheDir = " + cacheDir.getAbsolutePath());
SimpleCache simpleCache = new SimpleCache(cacheDir, new LeastRecentlyUsedCacheEvictor(64 * 1024 * 1024L));
cacheDataSourceFactory = new CacheDataSourceFactory(simpleCache, dataSourceFactory, CacheDataSource.FLAG_BLOCK_ON_CACHE, 512 * 1024);
}
}
public void initPlayer() {
if (DEBUG) Log.d(TAG, "initPlayer() called with: context = [" + context + "]");
initExoPlayerCache();
AdaptiveTrackSelection.Factory trackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
DefaultTrackSelector defaultTrackSelector = new DefaultTrackSelector(trackSelectionFactory);
DefaultLoadControl loadControl = new DefaultLoadControl();
simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(context, defaultTrackSelector, loadControl);
simpleExoPlayer.addListener(this);
}
public void initListeners() {
progressUpdate = new Runnable() {
@Override
public void run() {
//if(DEBUG) Log.d(TAG, "progressUpdate run() called");
onUpdateProgress((int) simpleExoPlayer.getCurrentPosition(), (int) simpleExoPlayer.getDuration(), simpleExoPlayer.getBufferedPercentage());
if (isProgressLoopRunning.get()) progressLoop.postDelayed(this, PROGRESS_LOOP_INTERVAL);
}
};
}
public void handleIntent(Intent intent) {
if (DEBUG) Log.d(TAG, "handleIntent() called with: intent = [" + intent + "]");
if (intent == null) return;
videoUrl = intent.getStringExtra(VIDEO_URL);
videoTitle = intent.getStringExtra(VIDEO_TITLE);
videoThumbnailUrl = intent.getStringExtra(VIDEO_THUMBNAIL_URL);
videoStartPos = intent.getIntExtra(START_POSITION, -1);
channelName = intent.getStringExtra(CHANNEL_NAME);
initThumbnail();
//play(getSelectedVideoStream(), true);
}
public void initThumbnail() {
if (DEBUG) Log.d(TAG, "initThumbnail() called");
videoThumbnail = null;
if (videoThumbnailUrl == null || videoThumbnailUrl.isEmpty()) return;
ImageLoader.getInstance().resume();
ImageLoader.getInstance().loadImage(videoThumbnailUrl, new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (DEBUG) Log.d(TAG, "onLoadingComplete() called with: imageUri = [" + imageUri + "], view = [" + view + "], loadedImage = [" + loadedImage + "]");
videoThumbnail = loadedImage;
onThumbnailReceived(loadedImage);
}
});
}
public void playUrl(String url, String format, boolean autoPlay) {
if (DEBUG) {
Log.d(TAG, "play() called with: url = [" + url + "], autoPlay = [" + autoPlay + "]");
}
if (url == null || simpleExoPlayer == null) {
RuntimeException runtimeException = new RuntimeException((url == null ? "Url " : "Player ") + " null");
onError(runtimeException);
throw runtimeException;
}
changeState(STATE_LOADING);
isPrepared = false;
mediaSource = buildMediaSource(url, format);
if (simpleExoPlayer.getPlaybackState() != ExoPlayer.STATE_IDLE) simpleExoPlayer.stop();
if (videoStartPos > 0) simpleExoPlayer.seekTo(videoStartPos);
simpleExoPlayer.prepare(mediaSource);
simpleExoPlayer.setPlayWhenReady(autoPlay);
}
public void destroyPlayer() {
if (DEBUG) Log.d(TAG, "destroyPlayer() called");
if (simpleExoPlayer != null) {
simpleExoPlayer.stop();
simpleExoPlayer.release();
}
if (progressLoop != null && isProgressLoopRunning.get()) stopProgressLoop();
}
public void destroy() {
if (DEBUG) Log.d(TAG, "destroy() called");
destroyPlayer();
unregisterBroadcastReceiver();
videoThumbnail = null;
simpleExoPlayer = null;
}
public MediaSource buildMediaSource(String url, String overrideExtension) {
if (DEBUG) {
Log.d(TAG, "buildMediaSource() called with: url = [" + url + "], overrideExtension = [" + overrideExtension + "]");
}
Uri uri = Uri.parse(url);
int type = TextUtils.isEmpty(overrideExtension) ? Util.inferContentType(uri) : Util.inferContentType("." + overrideExtension);
MediaSource mediaSource;
switch (type) {
case C.TYPE_SS:
mediaSource = new SsMediaSource(uri, cacheDataSourceFactory, new DefaultSsChunkSource.Factory(cacheDataSourceFactory), null, null);
break;
case C.TYPE_DASH:
mediaSource = new DashMediaSource(uri, cacheDataSourceFactory, new DefaultDashChunkSource.Factory(cacheDataSourceFactory), null, null);
break;
case C.TYPE_HLS:
mediaSource = new HlsMediaSource(uri, cacheDataSourceFactory, null, null);
break;
case C.TYPE_OTHER:
mediaSource = new ExtractorMediaSource(uri, cacheDataSourceFactory, extractorsFactory, null, null);
break;
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
return mediaSource;
}
/*//////////////////////////////////////////////////////////////////////////
// Broadcast Receiver
//////////////////////////////////////////////////////////////////////////*/
/**
* Add your action in the intentFilter
*
* @param intentFilter intent filter that will be used for register the receiver
*/
protected void setupBroadcastReceiver(IntentFilter intentFilter) {
intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
}
public void onBroadcastReceived(Intent intent) {
switch (intent.getAction()) {
case AudioManager.ACTION_AUDIO_BECOMING_NOISY:
if (isPlaying()) simpleExoPlayer.setPlayWhenReady(false);
break;
}
}
public void unregisterBroadcastReceiver() {
if (broadcastReceiver != null && context != null) {
context.unregisterReceiver(broadcastReceiver);
broadcastReceiver = null;
}
}
/*//////////////////////////////////////////////////////////////////////////
// AudioFocus
//////////////////////////////////////////////////////////////////////////*/
private static final int DUCK_DURATION = 1500;
private static final float DUCK_AUDIO_TO = .2f;
@Override
public void onAudioFocusChange(int focusChange) {
if (DEBUG) Log.d(TAG, "onAudioFocusChange() called with: focusChange = [" + focusChange + "]");
if (simpleExoPlayer == null) return;
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
onAudioFocusGain();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
onAudioFocusLossCanDuck();
break;
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
onAudioFocusLoss();
break;
}
}
protected void onAudioFocusGain() {
if (DEBUG) Log.d(TAG, "onAudioFocusGain() called");
if (simpleExoPlayer != null) simpleExoPlayer.setVolume(DUCK_AUDIO_TO);
animateAudio(DUCK_AUDIO_TO, 1f, DUCK_DURATION);
simpleExoPlayer.setPlayWhenReady(true);
}
protected void onAudioFocusLoss() {
if (DEBUG) Log.d(TAG, "onAudioFocusLoss() called");
simpleExoPlayer.setPlayWhenReady(false);
}
protected void onAudioFocusLossCanDuck() {
if (DEBUG) Log.d(TAG, "onAudioFocusLossCanDuck() called");
// Set the volume to 1/10 on ducking
animateAudio(simpleExoPlayer.getVolume(), DUCK_AUDIO_TO, DUCK_DURATION);
}
/*//////////////////////////////////////////////////////////////////////////
// States Implementation
//////////////////////////////////////////////////////////////////////////*/
public static final int STATE_LOADING = 123;
public static final int STATE_PLAYING = 124;
public static final int STATE_BUFFERING = 125;
public static final int STATE_PAUSED = 126;
public static final int STATE_PAUSED_SEEK = 127;
public static final int STATE_COMPLETED = 128;
protected int currentState = -1;
public void changeState(int state) {
if (DEBUG) Log.d(TAG, "changeState() called with: state = [" + state + "]");
currentState = state;
switch (state) {
case STATE_LOADING:
onLoading();
break;
case STATE_PLAYING:
onPlaying();
break;
case STATE_BUFFERING:
onBuffering();
break;
case STATE_PAUSED:
onPaused();
break;
case STATE_PAUSED_SEEK:
onPausedSeek();
break;
case STATE_COMPLETED:
onCompleted();
break;
}
}
public void onLoading() {
if (DEBUG) Log.d(TAG, "onLoading() called");
if (!isProgressLoopRunning.get()) startProgressLoop();
}
public void onPlaying() {
if (DEBUG) Log.d(TAG, "onPlaying() called");
if (!isProgressLoopRunning.get()) startProgressLoop();
}
public void onBuffering() {
}
public void onPaused() {
if (isProgressLoopRunning.get()) stopProgressLoop();
}
public void onPausedSeek() {
}
public void onCompleted() {
if (DEBUG) Log.d(TAG, "onCompleted() called");
if (isProgressLoopRunning.get()) stopProgressLoop();
if (currentRepeatMode == RepeatMode.REPEAT_ONE) {
changeState(STATE_LOADING);
simpleExoPlayer.seekTo(0);
}
}
/*//////////////////////////////////////////////////////////////////////////
// Repeat
//////////////////////////////////////////////////////////////////////////*/
protected RepeatMode currentRepeatMode = RepeatMode.REPEAT_DISABLED;
public enum RepeatMode {
REPEAT_DISABLED,
REPEAT_ONE,
REPEAT_ALL
}
public void onRepeatClicked() {
if (DEBUG) Log.d(TAG, "onRepeatClicked() called");
// TODO: implement repeat all when playlist is implemented
// Switch the modes between DISABLED and REPEAT_ONE, till playlist is implemented
setCurrentRepeatMode(getCurrentRepeatMode() == RepeatMode.REPEAT_DISABLED ?
RepeatMode.REPEAT_ONE :
RepeatMode.REPEAT_DISABLED);
if (DEBUG) Log.d(TAG, "onRepeatClicked() currentRepeatMode = " + getCurrentRepeatMode().name());
}
/*//////////////////////////////////////////////////////////////////////////
// ExoPlayer Listener
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
if (DEBUG) Log.d(TAG, "onLoadingChanged() called with: isLoading = [" + isLoading + "]");
if (!isLoading && getCurrentState() == STATE_PAUSED && isProgressLoopRunning.get()) stopProgressLoop();
else if (isLoading && !isProgressLoopRunning.get()) startProgressLoop();
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (DEBUG) Log.d(TAG, "onPlayerStateChanged() called with: playWhenReady = [" + playWhenReady + "], playbackState = [" + playbackState + "]");
if (getCurrentState() == STATE_PAUSED_SEEK) {
if (DEBUG) Log.d(TAG, "onPlayerStateChanged() currently on PausedSeek");
return;
}
switch (playbackState) {
case ExoPlayer.STATE_IDLE: // 1
isPrepared = false;
break;
case ExoPlayer.STATE_BUFFERING: // 2
if (isPrepared && getCurrentState() != STATE_LOADING) changeState(STATE_BUFFERING);
break;
case ExoPlayer.STATE_READY: //3
if (!isPrepared) {
isPrepared = true;
onPrepared(playWhenReady);
break;
}
if (currentState == STATE_PAUSED_SEEK) break;
changeState(playWhenReady ? STATE_PLAYING : STATE_PAUSED);
break;
case ExoPlayer.STATE_ENDED: // 4
changeState(STATE_COMPLETED);
isPrepared = false;
break;
}
}
@Override
public void onPlayerError(ExoPlaybackException error) {
if (DEBUG) Log.d(TAG, "onPlayerError() called with: error = [" + error + "]");
onError(error);
}
@Override
public void onPositionDiscontinuity() {
}
/*//////////////////////////////////////////////////////////////////////////
// General Player
//////////////////////////////////////////////////////////////////////////*/
public abstract void onError(Exception exception);
public void onPrepared(boolean playWhenReady) {
if (DEBUG) Log.d(TAG, "onPrepared() called with: playWhenReady = [" + playWhenReady + "]");
if (playWhenReady) audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
changeState(playWhenReady ? STATE_PLAYING : STATE_PAUSED);
}
public abstract void onUpdateProgress(int currentProgress, int duration, int bufferPercent);
public void onVideoPlayPause() {
if (DEBUG) Log.d(TAG, "onVideoPlayPause() called");
if (currentState == STATE_COMPLETED) {
onVideoPlayPauseRepeat();
return;
}
if (!isPlaying()) audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
else audioManager.abandonAudioFocus(null);
simpleExoPlayer.setPlayWhenReady(!isPlaying());
}
public void onVideoPlayPauseRepeat() {
if (DEBUG) Log.d(TAG, "onVideoPlayPauseRepeat() called");
changeState(STATE_LOADING);
setVideoStartPos(0);
simpleExoPlayer.seekTo(0);
simpleExoPlayer.setPlayWhenReady(true);
audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
public void onFastRewind() {
if (DEBUG) Log.d(TAG, "onFastRewind() called");
seekBy(-FAST_FORWARD_REWIND_AMOUNT);
}
public void onFastForward() {
if (DEBUG) Log.d(TAG, "onFastForward() called");
seekBy(FAST_FORWARD_REWIND_AMOUNT);
}
public void onThumbnailReceived(Bitmap thumbnail) {
if (DEBUG) Log.d(TAG, "onThumbnailReceived() called with: thumbnail = [" + thumbnail + "]");
}
public void seekBy(int milliSeconds) {
if (DEBUG) Log.d(TAG, "seekBy() called with: milliSeconds = [" + milliSeconds + "]");
if (simpleExoPlayer == null || (isCompleted() && milliSeconds > 0) || ((milliSeconds < 0 && simpleExoPlayer.getCurrentPosition() == 0))) return;
int progress = (int) (simpleExoPlayer.getCurrentPosition() + milliSeconds);
if (progress < 0) progress = 0;
simpleExoPlayer.seekTo(progress);
}
public boolean isPlaying() {
return simpleExoPlayer.getPlaybackState() == ExoPlayer.STATE_READY && simpleExoPlayer.getPlayWhenReady();
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
private final StringBuilder stringBuilder = new StringBuilder();
private final Formatter formatter = new Formatter(stringBuilder, Locale.getDefault());
public String getTimeString(int milliSeconds) {
long seconds = (milliSeconds % 60000L) / 1000L;
long minutes = (milliSeconds % 3600000L) / 60000L;
long hours = (milliSeconds % 86400000L) / 3600000L;
long days = (milliSeconds % (86400000L * 7L)) / 86400000L;
stringBuilder.setLength(0);
return days > 0 ? formatter.format("%d:%02d:%02d:%02d", days, hours, minutes, seconds).toString()
: hours > 0 ? formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
: formatter.format("%02d:%02d", minutes, seconds).toString();
}
protected void startProgressLoop() {
progressLoop.removeCallbacksAndMessages(null);
isProgressLoopRunning.set(true);
progressLoop.post(progressUpdate);
}
protected void stopProgressLoop() {
isProgressLoopRunning.set(false);
progressLoop.removeCallbacksAndMessages(null);
}
protected void tryDeleteCacheFiles(Context context) {
File cacheDir = new File(context.getExternalCacheDir(), CACHE_FOLDER_NAME);
if (cacheDir.exists()) {
try {
if (cacheDir.isDirectory()) {
for (File file : cacheDir.listFiles()) {
try {
if (DEBUG) Log.d(TAG, "tryDeleteCacheFiles: " + file.getAbsolutePath() + " deleted = " + file.delete());
} catch (Exception ignored) {
}
}
}
} catch (Exception ignored) {
}
}
}
public void triggerProgressUpdate() {
onUpdateProgress((int) simpleExoPlayer.getCurrentPosition(), (int) simpleExoPlayer.getDuration(), simpleExoPlayer.getBufferedPercentage());
}
public void animateAudio(final float from, final float to, int duration) {
ValueAnimator valueAnimator = new ValueAnimator();
valueAnimator.setFloatValues(from, to);
valueAnimator.setDuration(duration);
valueAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
if (simpleExoPlayer != null) simpleExoPlayer.setVolume(from);
}
@Override
public void onAnimationCancel(Animator animation) {
if (simpleExoPlayer != null) simpleExoPlayer.setVolume(to);
}
@Override
public void onAnimationEnd(Animator animation) {
if (simpleExoPlayer != null) simpleExoPlayer.setVolume(to);
}
});
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (simpleExoPlayer != null) simpleExoPlayer.setVolume(((float) animation.getAnimatedValue()));
}
});
valueAnimator.start();
}
/*//////////////////////////////////////////////////////////////////////////
// Getters and Setters
//////////////////////////////////////////////////////////////////////////*/
public SimpleExoPlayer getPlayer() {
return simpleExoPlayer;
}
public SharedPreferences getSharedPreferences() {
return sharedPreferences;
}
public RepeatMode getCurrentRepeatMode() {
return currentRepeatMode;
}
public void setCurrentRepeatMode(RepeatMode mode) {
currentRepeatMode = mode;
}
public int getCurrentState() {
return currentState;
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
public int getVideoStartPos() {
return videoStartPos;
}
public void setVideoStartPos(int videoStartPos) {
this.videoStartPos = videoStartPos;
}
public String getVideoTitle() {
return videoTitle;
}
public void setVideoTitle(String videoTitle) {
this.videoTitle = videoTitle;
}
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public boolean isCompleted() {
return simpleExoPlayer != null && simpleExoPlayer.getPlaybackState() == ExoPlayer.STATE_ENDED;
}
public boolean isPrepared() {
return isPrepared;
}
public void setPrepared(boolean prepared) {
isPrepared = prepared;
}
public Bitmap getVideoThumbnail() {
return videoThumbnail;
}
public void setVideoThumbnail(Bitmap videoThumbnail) {
this.videoThumbnail = videoThumbnail;
}
public String getVideoThumbnailUrl() {
return videoThumbnailUrl;
}
public void setVideoThumbnailUrl(String videoThumbnailUrl) {
this.videoThumbnailUrl = videoThumbnailUrl;
}
}

View File

@@ -0,0 +1,549 @@
package org.schabi.newpipe.player;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import org.schabi.newpipe.R;
import org.schabi.newpipe.util.NavigationHelper;
import org.schabi.newpipe.util.PermissionHelper;
import org.schabi.newpipe.util.ThemeHelper;
/**
* Activity Player implementing VideoPlayer
*
* @author mauriciocolli
*/
public class MainVideoPlayer extends Activity {
private static final String TAG = ".MainVideoPlayer";
private static final boolean DEBUG = BasePlayer.DEBUG;
private AudioManager audioManager;
private GestureDetector gestureDetector;
private final Runnable hideUiRunnable = new Runnable() {
@Override
public void run() {
hideSystemUi();
}
};
private boolean activityPaused;
private VideoPlayerImpl playerImpl;
/*//////////////////////////////////////////////////////////////////////////
// Activity LifeCycle
//////////////////////////////////////////////////////////////////////////*/
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate() called with: savedInstanceState = [" + savedInstanceState + "]");
ThemeHelper.setTheme(this, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) getWindow().setStatusBarColor(Color.BLACK);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (getIntent() == null) {
Toast.makeText(this, R.string.general_error, Toast.LENGTH_SHORT).show();
finish();
return;
}
showSystemUi();
setContentView(R.layout.activity_exo_player);
playerImpl = new VideoPlayerImpl();
playerImpl.setup(findViewById(android.R.id.content));
playerImpl.handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
if (DEBUG) Log.d(TAG, "onNewIntent() called with: intent = [" + intent + "]");
super.onNewIntent(intent);
playerImpl.handleIntent(intent);
}
@Override
public void onBackPressed() {
if (DEBUG) Log.d(TAG, "onBackPressed() called");
super.onBackPressed();
if (playerImpl.isPlaying()) playerImpl.getPlayer().setPlayWhenReady(false);
}
@Override
protected void onStop() {
super.onStop();
if (DEBUG) Log.d(TAG, "onStop() called");
activityPaused = true;
if (playerImpl.getPlayer() != null) {
playerImpl.setVideoStartPos((int) playerImpl.getPlayer().getCurrentPosition());
playerImpl.destroyPlayer();
}
}
@Override
protected void onResume() {
super.onResume();
if (DEBUG) Log.d(TAG, "onResume() called");
if (activityPaused) {
playerImpl.initPlayer();
playerImpl.getPlayPauseButton().setImageResource(R.drawable.ic_play_arrow_white);
playerImpl.play(false);
activityPaused = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (DEBUG) Log.d(TAG, "onDestroy() called");
if (playerImpl != null) playerImpl.destroy();
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
private void showSystemUi() {
if (DEBUG) Log.d(TAG, "showSystemUi() called");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
);
} else getWindow().getDecorView().setSystemUiVisibility(0);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void hideSystemUi() {
if (DEBUG) Log.d(TAG, "hideSystemUi() called");
if (android.os.Build.VERSION.SDK_INT >= 16) {
int visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) visibility |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
getWindow().getDecorView().setSystemUiVisibility(visibility);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void toggleOrientation() {
setRequestedOrientation(getResources().getDisplayMetrics().heightPixels > getResources().getDisplayMetrics().widthPixels
? ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
: ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
///////////////////////////////////////////////////////////////////////////
@SuppressWarnings({"unused", "WeakerAccess"})
private class VideoPlayerImpl extends VideoPlayer {
private TextView titleTextView;
private TextView channelTextView;
private TextView volumeTextView;
private TextView brightnessTextView;
private ImageButton repeatButton;
private ImageButton screenRotationButton;
private ImageButton playPauseButton;
VideoPlayerImpl() {
super("VideoPlayerImpl" + MainVideoPlayer.TAG, MainVideoPlayer.this);
}
@Override
public void initViews(View rootView) {
super.initViews(rootView);
this.titleTextView = (TextView) rootView.findViewById(R.id.titleTextView);
this.channelTextView = (TextView) rootView.findViewById(R.id.channelTextView);
this.volumeTextView = (TextView) rootView.findViewById(R.id.volumeTextView);
this.brightnessTextView = (TextView) rootView.findViewById(R.id.brightnessTextView);
this.repeatButton = (ImageButton) rootView.findViewById(R.id.repeatButton);
this.screenRotationButton = (ImageButton) rootView.findViewById(R.id.screenRotationButton);
this.playPauseButton = (ImageButton) rootView.findViewById(R.id.playPauseButton);
// Due to a bug on lower API, lets set the alpha instead of using a drawable
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) repeatButton.setImageAlpha(77);
else { //noinspection deprecation
repeatButton.setAlpha(77);
}
}
@Override
public void initListeners() {
super.initListeners();
MySimpleOnGestureListener listener = new MySimpleOnGestureListener();
gestureDetector = new GestureDetector(context, listener);
gestureDetector.setIsLongpressEnabled(false);
playerImpl.getRootView().setOnTouchListener(listener);
repeatButton.setOnClickListener(this);
playPauseButton.setOnClickListener(this);
screenRotationButton.setOnClickListener(this);
}
@Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
titleTextView.setText(getVideoTitle());
channelTextView.setText(getChannelName());
}
@Override
public void playUrl(String url, String format, boolean autoPlay) {
super.playUrl(url, format, autoPlay);
playPauseButton.setImageResource(autoPlay ? R.drawable.ic_pause_white : R.drawable.ic_play_arrow_white);
}
@Override
public void onFullScreenButtonClicked() {
if (DEBUG) Log.d(TAG, "onFullScreenButtonClicked() called");
if (playerImpl.getPlayer() == null) return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !PermissionHelper.checkSystemAlertWindowPermission(MainVideoPlayer.this)) {
Toast.makeText(MainVideoPlayer.this, R.string.msg_popup_permission, Toast.LENGTH_LONG).show();
return;
}
context.startService(NavigationHelper.getOpenVideoPlayerIntent(context, PopupVideoPlayer.class, playerImpl));
if (playerImpl != null) playerImpl.destroyPlayer();
((View) getControlAnimationView().getParent()).setVisibility(View.GONE);
MainVideoPlayer.this.finish();
}
@Override
@SuppressWarnings("deprecation")
public void onRepeatClicked() {
super.onRepeatClicked();
if (DEBUG) Log.d(TAG, "onRepeatClicked() called");
switch (getCurrentRepeatMode()) {
case REPEAT_DISABLED:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) repeatButton.setImageAlpha(77);
else repeatButton.setAlpha(77);
break;
case REPEAT_ONE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) repeatButton.setImageAlpha(255);
else repeatButton.setAlpha(255);
break;
case REPEAT_ALL:
// Waiting :)
break;
}
}
@Override
public void onClick(View v) {
super.onClick(v);
if (v.getId() == repeatButton.getId()) onRepeatClicked();
else if (v.getId() == playPauseButton.getId()) onVideoPlayPause();
else if (v.getId() == screenRotationButton.getId()) onScreenRotationClicked();
if (getCurrentState() != STATE_COMPLETED) {
animateView(playerImpl.getControlsRoot(), true, 300, 0, new Runnable() {
@Override
public void run() {
if (getCurrentState() == STATE_PLAYING && !playerImpl.isQualityMenuVisible()) {
animateView(playerImpl.getControlsRoot(), false, 300, DEFAULT_CONTROLS_HIDE_TIME, true);
}
}
}, false);
}
}
private void onScreenRotationClicked() {
if (DEBUG) Log.d(TAG, "onScreenRotationClicked() called");
toggleOrientation();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
super.onStopTrackingTouch(seekBar);
if (playerImpl.wasPlaying()) {
animateView(playerImpl.getControlsRoot(), false, 100, 0);
}
}
@Override
public void onDismiss(PopupMenu menu) {
super.onDismiss(menu);
if (isPlaying()) animateView(getControlsRoot(), false, 500, 0);
}
@Override
public void onError(Exception exception) {
exception.printStackTrace();
Toast.makeText(context, "Failed to play this video", Toast.LENGTH_SHORT).show();
finish();
}
/*//////////////////////////////////////////////////////////////////////////
// States
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onLoading() {
super.onLoading();
playPauseButton.setImageResource(R.drawable.ic_pause_white);
animateView(playPauseButton, false, 100, 0);
}
@Override
public void onBuffering() {
super.onBuffering();
animateView(playPauseButton, false, 100, 0);
}
@Override
public void onPlaying() {
super.onPlaying();
//playPauseButton.setImageResource(R.drawable.ic_pause_white);
//animateView(playPauseButton, true, 500, 0);
animateView(playPauseButton, false, 80, 0, new Runnable() {
@Override
public void run() {
playPauseButton.setImageResource(R.drawable.ic_pause_white);
animateView(playPauseButton, true, 200, 0);
}
});
showSystemUi();
}
@Override
public void onPaused() {
super.onPaused();
//playPauseButton.setImageResource(R.drawable.ic_play_arrow_white);
//animateView(playPauseButton, true, 100, 0);
animateView(playPauseButton, false, 80, 0, new Runnable() {
@Override
public void run() {
playPauseButton.setImageResource(R.drawable.ic_play_arrow_white);
animateView(playPauseButton, true, 200, 0);
}
});
showSystemUi();
}
@Override
public void onPausedSeek() {
super.onPausedSeek();
animateView(playPauseButton, false, 100, 0);
}
@Override
public void onCompleted() {
if (getCurrentRepeatMode() == RepeatMode.REPEAT_ONE) {
playPauseButton.setImageResource(R.drawable.ic_pause_white);
} else {
showSystemUi();
animateView(playPauseButton, false, 0, 0, new Runnable() {
@Override
public void run() {
playPauseButton.setImageResource(R.drawable.ic_replay_white);
animateView(playPauseButton, true, 300, 0);
}
});
}
super.onCompleted();
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
@Override
public void animateView(View view, boolean enterOrExit, long duration, long delay, final Runnable execOnEnd, boolean hideUi) {
//if (execOnEnd == null) playerImpl.setDefaultAnimationEnd(hideUiRunnable);
if (hideUi && execOnEnd != null) {
Runnable combinedRunnable = new Runnable() {
@Override
public void run() {
execOnEnd.run();
hideUiRunnable.run();
}
};
super.animateView(view, enterOrExit, duration, delay, combinedRunnable, true);
} else super.animateView(view, enterOrExit, duration, delay, hideUi ? hideUiRunnable : execOnEnd, hideUi);
}
///////////////////////////////////////////////////////////////////////////
// Getters
///////////////////////////////////////////////////////////////////////////
public TextView getTitleTextView() {
return titleTextView;
}
public TextView getChannelTextView() {
return channelTextView;
}
public TextView getVolumeTextView() {
return volumeTextView;
}
public TextView getBrightnessTextView() {
return brightnessTextView;
}
public ImageButton getRepeatButton() {
return repeatButton;
}
public ImageButton getPlayPauseButton() {
return playPauseButton;
}
}
private class MySimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener implements View.OnTouchListener {
private boolean isMoving;
@Override
public boolean onDoubleTap(MotionEvent e) {
if (DEBUG) Log.d(TAG, "onDoubleTap() called with: e = [" + e + "]" + "rawXy = " + e.getRawX() + ", " + e.getRawY() + ", xy = " + e.getX() + ", " + e.getY());
if (!playerImpl.isPlaying()) return false;
if (e.getX() > playerImpl.getRootView().getWidth() / 2) playerImpl.onFastForward();
else playerImpl.onFastRewind();
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (DEBUG) Log.d(TAG, "onSingleTapConfirmed() called with: e = [" + e + "]");
if (playerImpl.getCurrentState() != BasePlayer.STATE_PLAYING) return true;
if (playerImpl.isControlsVisible()) playerImpl.animateView(playerImpl.getControlsRoot(), false, 150, 0, true);
else {
playerImpl.animateView(playerImpl.getControlsRoot(), true, 500, 0, new Runnable() {
@Override
public void run() {
playerImpl.animateView(playerImpl.getControlsRoot(), false, 300, VideoPlayer.DEFAULT_CONTROLS_HIDE_TIME, true);
}
});
showSystemUi();
}
return true;
}
private final float stepsBrightness = 15, stepBrightness = (1f / stepsBrightness), minBrightness = .01f;
private float currentBrightness = .5f;
private int currentVolume, maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
private final float stepsVolume = 15, stepVolume = (float) Math.ceil(maxVolume / stepsVolume), minVolume = 0;
private final String brightnessUnicode = new String(Character.toChars(0x2600));
private final String volumeUnicode = new String(Character.toChars(0x1F508));
private final int MOVEMENT_THRESHOLD = 40;
private final int eventsThreshold = 8;
private boolean triggered = false;
private int eventsNum;
// TODO: Improve video gesture controls
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
//noinspection PointlessBooleanExpression
if (DEBUG && true) Log.d(TAG, "MainVideoPlayer.onScroll = " +
", e1.getRaw = [" + e1.getRawX() + ", " + e1.getRawY() + "]" +
", e2.getRaw = [" + e2.getRawX() + ", " + e2.getRawY() + "]" +
", distanceXy = [" + distanceX + ", " + distanceY + "]");
float abs = Math.abs(e2.getY() - e1.getY());
if (!triggered) {
triggered = abs > MOVEMENT_THRESHOLD;
return false;
}
if (eventsNum++ % eventsThreshold != 0 || playerImpl.getCurrentState() == BasePlayer.STATE_COMPLETED) return false;
isMoving = true;
// boolean up = !((e2.getY() - e1.getY()) > 0) && distanceY > 0; // Android's origin point is on top
boolean up = distanceY > 0;
if (e1.getX() > playerImpl.getRootView().getWidth() / 2) {
double floor = Math.floor(up ? stepVolume : -stepVolume);
currentVolume = (int) (audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) + floor);
if (currentVolume >= maxVolume) currentVolume = maxVolume;
if (currentVolume <= minVolume) currentVolume = (int) minVolume;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
if (DEBUG) Log.d(TAG, "onScroll().volumeControl, currentVolume = " + currentVolume);
playerImpl.getVolumeTextView().setText(volumeUnicode + " " + Math.round((((float) currentVolume) / maxVolume) * 100) + "%");
if (playerImpl.getVolumeTextView().getVisibility() != View.VISIBLE) playerImpl.animateView(playerImpl.getVolumeTextView(), true, 200, 0);
if (playerImpl.getBrightnessTextView().getVisibility() == View.VISIBLE) playerImpl.getBrightnessTextView().setVisibility(View.GONE);
} else {
WindowManager.LayoutParams lp = getWindow().getAttributes();
currentBrightness += up ? stepBrightness : -stepBrightness;
if (currentBrightness >= 1f) currentBrightness = 1f;
if (currentBrightness <= minBrightness) currentBrightness = minBrightness;
lp.screenBrightness = currentBrightness;
getWindow().setAttributes(lp);
if (DEBUG) Log.d(TAG, "onScroll().brightnessControl, currentBrightness = " + currentBrightness);
int brightnessNormalized = Math.round(currentBrightness * 100);
playerImpl.getBrightnessTextView().setText(brightnessUnicode + " " + (brightnessNormalized == 1 ? 0 : brightnessNormalized) + "%");
if (playerImpl.getBrightnessTextView().getVisibility() != View.VISIBLE) playerImpl.animateView(playerImpl.getBrightnessTextView(), true, 200, 0);
if (playerImpl.getVolumeTextView().getVisibility() == View.VISIBLE) playerImpl.getVolumeTextView().setVisibility(View.GONE);
}
return true;
}
private void onScrollEnd() {
if (DEBUG) Log.d(TAG, "onScrollEnd() called");
triggered = false;
eventsNum = 0;
/* if (playerImpl.getVolumeTextView().getVisibility() == View.VISIBLE) playerImpl.getVolumeTextView().setVisibility(View.GONE);
if (playerImpl.getBrightnessTextView().getVisibility() == View.VISIBLE) playerImpl.getBrightnessTextView().setVisibility(View.GONE);*/
if (playerImpl.getVolumeTextView().getVisibility() == View.VISIBLE) playerImpl.animateView(playerImpl.getVolumeTextView(), false, 200, 200);
if (playerImpl.getBrightnessTextView().getVisibility() == View.VISIBLE) playerImpl.animateView(playerImpl.getBrightnessTextView(), false, 200, 200);
if (playerImpl.isControlsVisible() && playerImpl.getCurrentState() == BasePlayer.STATE_PLAYING) {
playerImpl.animateView(playerImpl.getControlsRoot(), false, 300, VideoPlayer.DEFAULT_CONTROLS_HIDE_TIME);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP && isMoving) {
isMoving = false;
onScrollEnd();
}
return true;
}
}
}

View File

@@ -1,12 +1,12 @@
package org.schabi.newpipe;
package org.schabi.newpipe.player;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@@ -27,6 +27,8 @@ import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.VideoView;
import org.schabi.newpipe.R;
/**
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* PlayVideoActivity.java is part of NewPipe.
@@ -62,14 +64,14 @@ public class PlayVideoActivity extends AppCompatActivity {
private ActionBar actionBar;
private VideoView videoView;
private int position = 0;
private int position;
private MediaController mediaController;
private ProgressBar progressBar;
private View decorView;
private boolean uiIsHidden = false;
private static long lastUiShowTime = 0;
private boolean uiIsHidden;
private static long lastUiShowTime;
private boolean isLandscape = true;
private boolean hasSoftKeys = false;
private boolean hasSoftKeys;
private SharedPreferences prefs;
private static final String PREF_IS_LANDSCAPE = "is_landscape";
@@ -80,6 +82,10 @@ public class PlayVideoActivity extends AppCompatActivity {
setContentView(R.layout.activity_play_video);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
//set background arrow style
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp);
isLandscape = checkIfLandscape();
hasSoftKeys = checkIfHasSoftKeys();
@@ -191,7 +197,6 @@ public class PlayVideoActivity extends AppCompatActivity {
@Override
public void onResume() {
super.onResume();
App.checkStartTor(this);
}
@Override
@@ -320,7 +325,7 @@ public class PlayVideoActivity extends AppCompatActivity {
int realHeight = realDisplayMetrics.heightPixels;
int displayHeight = displayMetrics.heightPixels;
return (realHeight - displayHeight);
return realHeight - displayHeight;
} else {
return 50;
}
@@ -337,7 +342,7 @@ public class PlayVideoActivity extends AppCompatActivity {
int realWidth = realDisplayMetrics.widthPixels;
int displayWidth = displayMetrics.widthPixels;
return (realWidth - displayWidth);
return realWidth - displayWidth;
} else {
return 50;
}

View File

@@ -0,0 +1,629 @@
package org.schabi.newpipe.player;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupMenu;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import org.schabi.newpipe.BuildConfig;
import org.schabi.newpipe.MainActivity;
import org.schabi.newpipe.R;
import org.schabi.newpipe.ReCaptchaActivity;
import org.schabi.newpipe.extractor.MediaFormat;
import org.schabi.newpipe.extractor.StreamingService;
import org.schabi.newpipe.extractor.stream_info.StreamInfo;
import org.schabi.newpipe.util.Constants;
import org.schabi.newpipe.util.NavigationHelper;
import org.schabi.newpipe.util.ThemeHelper;
import org.schabi.newpipe.util.Utils;
import org.schabi.newpipe.workers.StreamExtractorWorker;
/**
* Service Popup Player implementing VideoPlayer
*
* @author mauriciocolli
*/
public class PopupVideoPlayer extends Service {
private static final String TAG = ".PopupVideoPlayer";
private static final boolean DEBUG = BasePlayer.DEBUG;
private static final int NOTIFICATION_ID = 40028922;
public static final String ACTION_CLOSE = "org.schabi.newpipe.player.PopupVideoPlayer.CLOSE";
public static final String ACTION_PLAY_PAUSE = "org.schabi.newpipe.player.PopupVideoPlayer.PLAY_PAUSE";
public static final String ACTION_OPEN_DETAIL = "org.schabi.newpipe.player.PopupVideoPlayer.OPEN_DETAIL";
public static final String ACTION_REPEAT = "org.schabi.newpipe.player.PopupVideoPlayer.REPEAT";
private WindowManager windowManager;
private WindowManager.LayoutParams windowLayoutParams;
private GestureDetector gestureDetector;
private float screenWidth, screenHeight;
private float popupWidth, popupHeight;
private float currentPopupHeight = 110.0f * Resources.getSystem().getDisplayMetrics().density;
//private float minimumHeight = 100; // TODO: Use it when implementing the resize of the popup
private final String setAlphaMethodName = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) ? "setImageAlpha" : "setAlpha";
private NotificationManager notificationManager;
private NotificationCompat.Builder notBuilder;
private RemoteViews notRemoteView;
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder().cacheInMemory(true).build();
private VideoPlayerImpl playerImpl;
private StreamExtractorWorker currentExtractorWorker;
/*//////////////////////////////////////////////////////////////////////////
// Service LifeCycle
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onCreate() {
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
notificationManager = ((NotificationManager) getSystemService(NOTIFICATION_SERVICE));
playerImpl = new VideoPlayerImpl();
ThemeHelper.setTheme(this, false);
}
@Override
@SuppressWarnings("unchecked")
public int onStartCommand(final Intent intent, int flags, int startId) {
if (DEBUG) Log.d(TAG, "onStartCommand() called with: intent = [" + intent + "], flags = [" + flags + "], startId = [" + startId + "]");
if (playerImpl.getPlayer() == null) initPopup();
if (!playerImpl.isPlaying()) playerImpl.getPlayer().setPlayWhenReady(true);
if (imageLoader != null) imageLoader.clearMemoryCache();
if (intent.getStringExtra(Constants.KEY_URL) != null) {
playerImpl.setStartedFromNewPipe(false);
currentExtractorWorker = new StreamExtractorWorker(this, 0, intent.getStringExtra(Constants.KEY_URL), new FetcherRunnable(this));
currentExtractorWorker.start();
} else {
playerImpl.setStartedFromNewPipe(true);
playerImpl.handleIntent(intent);
}
return START_NOT_STICKY;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
updateScreenSize();
}
@Override
public void onDestroy() {
if (DEBUG) Log.d(TAG, "onDestroy() called");
stopForeground(true);
if (playerImpl != null) {
playerImpl.destroy();
if (playerImpl.getRootView() != null) windowManager.removeView(playerImpl.getRootView());
}
if (imageLoader != null) imageLoader.clearMemoryCache();
if (notificationManager != null) notificationManager.cancel(NOTIFICATION_ID);
if (currentExtractorWorker != null) {
currentExtractorWorker.cancel();
currentExtractorWorker = null;
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*//////////////////////////////////////////////////////////////////////////
// Init
//////////////////////////////////////////////////////////////////////////*/
@SuppressLint("RtlHardcoded")
private void initPopup() {
if (DEBUG) Log.d(TAG, "initPopup() called");
View rootView = View.inflate(this, R.layout.player_popup, null);
playerImpl.setup(rootView);
updateScreenSize();
windowLayoutParams = new WindowManager.LayoutParams(
(int) getMinimumVideoWidth(currentPopupHeight), (int) currentPopupHeight,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
windowLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
MySimpleOnGestureListener listener = new MySimpleOnGestureListener();
gestureDetector = new GestureDetector(this, listener);
gestureDetector.setIsLongpressEnabled(false);
rootView.setOnTouchListener(listener);
playerImpl.getLoadingPanel().setMinimumWidth(windowLayoutParams.width);
playerImpl.getLoadingPanel().setMinimumHeight(windowLayoutParams.height);
windowManager.addView(rootView, windowLayoutParams);
}
/*//////////////////////////////////////////////////////////////////////////
// Notification
//////////////////////////////////////////////////////////////////////////*/
private NotificationCompat.Builder createNotification() {
notRemoteView = new RemoteViews(BuildConfig.APPLICATION_ID, R.layout.player_popup_notification);
if (playerImpl.getVideoThumbnail() == null) notRemoteView.setImageViewResource(R.id.notificationCover, R.drawable.dummy_thumbnail);
else notRemoteView.setImageViewBitmap(R.id.notificationCover, playerImpl.getVideoThumbnail());
notRemoteView.setTextViewText(R.id.notificationSongName, playerImpl.getVideoTitle());
notRemoteView.setTextViewText(R.id.notificationArtist, playerImpl.getChannelName());
notRemoteView.setOnClickPendingIntent(R.id.notificationPlayPause,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_PLAY_PAUSE), PendingIntent.FLAG_UPDATE_CURRENT));
notRemoteView.setOnClickPendingIntent(R.id.notificationStop,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_CLOSE), PendingIntent.FLAG_UPDATE_CURRENT));
notRemoteView.setOnClickPendingIntent(R.id.notificationContent,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_OPEN_DETAIL), PendingIntent.FLAG_UPDATE_CURRENT));
notRemoteView.setOnClickPendingIntent(R.id.notificationRepeat,
PendingIntent.getBroadcast(this, NOTIFICATION_ID, new Intent(ACTION_REPEAT), PendingIntent.FLAG_UPDATE_CURRENT));
switch (playerImpl.getCurrentRepeatMode()) {
case REPEAT_DISABLED:
notRemoteView.setInt(R.id.notificationRepeat, setAlphaMethodName, 77);
break;
case REPEAT_ONE:
notRemoteView.setInt(R.id.notificationRepeat, setAlphaMethodName, 255);
break;
case REPEAT_ALL:
// Waiting :)
break;
}
return new NotificationCompat.Builder(this)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_play_arrow_white)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContent(notRemoteView);
}
/**
* Updates the notification, and the play/pause button in it.
* Used for changes on the remoteView
*
* @param drawableId if != -1, sets the drawable with that id on the play/pause button
*/
private void updateNotification(int drawableId) {
if (DEBUG) Log.d(TAG, "updateNotification() called with: drawableId = [" + drawableId + "]");
if (notBuilder == null || notRemoteView == null) return;
if (drawableId != -1) notRemoteView.setImageViewResource(R.id.notificationPlayPause, drawableId);
notificationManager.notify(NOTIFICATION_ID, notBuilder.build());
}
/*//////////////////////////////////////////////////////////////////////////
// Misc
//////////////////////////////////////////////////////////////////////////*/
public void onVideoClose() {
if (DEBUG) Log.d(TAG, "onVideoClose() called");
stopSelf();
}
public void onOpenDetail(Context context, String videoUrl, String videoTitle) {
if (DEBUG) Log.d(TAG, "onOpenDetail() called with: context = [" + context + "], videoUrl = [" + videoUrl + "]");
Intent i = new Intent(context, MainActivity.class);
i.putExtra(Constants.KEY_SERVICE_ID, 0);
i.putExtra(Constants.KEY_URL, videoUrl);
i.putExtra(Constants.KEY_TITLE, videoTitle);
i.putExtra(Constants.KEY_LINK_TYPE, StreamingService.LinkType.STREAM);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
private float getMinimumVideoWidth(float height) {
float width = height * (16.0f / 9.0f); // Respect the 16:9 ratio that most videos have
if (DEBUG) Log.d(TAG, "getMinimumVideoWidth() called with: height = [" + height + "], returned: " + width);
return width;
}
private void updateScreenSize() {
DisplayMetrics metrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
if (DEBUG) Log.d(TAG, "updateScreenSize() called > screenWidth = " + screenWidth + ", screenHeight = " + screenHeight);
}
///////////////////////////////////////////////////////////////////////////
private class VideoPlayerImpl extends VideoPlayer {
VideoPlayerImpl() {
super("VideoPlayerImpl" + PopupVideoPlayer.TAG, PopupVideoPlayer.this);
}
@Override
public void playUrl(String url, String format, boolean autoPlay) {
super.playUrl(url, format, autoPlay);
windowLayoutParams.width = (int) getMinimumVideoWidth(currentPopupHeight);
windowManager.updateViewLayout(getRootView(), windowLayoutParams);
notBuilder = createNotification();
startForeground(NOTIFICATION_ID, notBuilder.build());
}
@Override
public void destroy() {
super.destroy();
if (notRemoteView != null) notRemoteView.setImageViewBitmap(R.id.notificationCover, null);
}
@Override
public void onThumbnailReceived(Bitmap thumbnail) {
super.onThumbnailReceived(thumbnail);
if (thumbnail != null) {
if (notRemoteView != null) notRemoteView.setImageViewBitmap(R.id.notificationCover, thumbnail);
updateNotification(-1);
}
}
@Override
public void onFullScreenButtonClicked() {
if (DEBUG) Log.d(TAG, "onFullScreenButtonClicked() called");
Intent intent;
if (!getSharedPreferences().getBoolean(getResources().getString(R.string.use_old_player_key), false)) {
intent = NavigationHelper.getOpenVideoPlayerIntent(context, MainVideoPlayer.class, playerImpl);
if (!playerImpl.isStartedFromNewPipe()) intent.putExtra(VideoPlayer.STARTED_FROM_NEWPIPE, false);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} else {
intent = new Intent(PopupVideoPlayer.this, PlayVideoActivity.class)
.putExtra(PlayVideoActivity.VIDEO_TITLE, getVideoTitle())
.putExtra(PlayVideoActivity.STREAM_URL, getSelectedStreamUri().toString())
.putExtra(PlayVideoActivity.VIDEO_URL, getVideoUrl())
.putExtra(PlayVideoActivity.START_POSITION, Math.round(getPlayer().getCurrentPosition() / 1000f));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
if (playerImpl != null) playerImpl.destroyPlayer();
stopSelf();
}
@Override
public void onRepeatClicked() {
super.onRepeatClicked();
switch (getCurrentRepeatMode()) {
case REPEAT_DISABLED:
// Drawable didn't work on low API :/
//notRemoteView.setImageViewResource(R.id.notificationRepeat, R.drawable.ic_repeat_disabled_white);
// Set the icon to 30% opacity - 255 (max) * .3
notRemoteView.setInt(R.id.notificationRepeat, setAlphaMethodName, 77);
break;
case REPEAT_ONE:
notRemoteView.setInt(R.id.notificationRepeat, setAlphaMethodName, 255);
break;
case REPEAT_ALL:
// Waiting :)
break;
}
updateNotification(-1);
}
@Override
public void onDismiss(PopupMenu menu) {
super.onDismiss(menu);
if (isPlaying()) animateView(getControlsRoot(), false, 500, 0);
}
@Override
public void onError(Exception exception) {
exception.printStackTrace();
Toast.makeText(context, "Failed to play this video", Toast.LENGTH_SHORT).show();
stopSelf();
}
/*//////////////////////////////////////////////////////////////////////////
// Broadcast Receiver
//////////////////////////////////////////////////////////////////////////*/
@Override
protected void setupBroadcastReceiver(IntentFilter intentFilter) {
super.setupBroadcastReceiver(intentFilter);
if (DEBUG) Log.d(TAG, "setupBroadcastReceiver() called with: intentFilter = [" + intentFilter + "]");
intentFilter.addAction(ACTION_CLOSE);
intentFilter.addAction(ACTION_PLAY_PAUSE);
intentFilter.addAction(ACTION_OPEN_DETAIL);
intentFilter.addAction(ACTION_REPEAT);
}
@Override
public void onBroadcastReceived(Intent intent) {
super.onBroadcastReceived(intent);
if (DEBUG) Log.d(TAG, "onBroadcastReceived() called with: intent = [" + intent + "]");
switch (intent.getAction()) {
case ACTION_CLOSE:
onVideoClose();
break;
case ACTION_PLAY_PAUSE:
playerImpl.onVideoPlayPause();
break;
case ACTION_OPEN_DETAIL:
onOpenDetail(PopupVideoPlayer.this, playerImpl.getVideoUrl(), playerImpl.getVideoTitle());
break;
case ACTION_REPEAT:
playerImpl.onRepeatClicked();
break;
}
}
/*//////////////////////////////////////////////////////////////////////////
// States
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onLoading() {
super.onLoading();
updateNotification(R.drawable.ic_play_arrow_white);
}
@Override
public void onPlaying() {
super.onPlaying();
updateNotification(R.drawable.ic_pause_white);
}
@Override
public void onBuffering() {
super.onBuffering();
updateNotification(R.drawable.ic_play_arrow_white);
}
@Override
public void onPaused() {
super.onPaused();
updateNotification(R.drawable.ic_play_arrow_white);
showAndAnimateControl(R.drawable.ic_play_arrow_white, false);
}
@Override
public void onPausedSeek() {
super.onPausedSeek();
updateNotification(R.drawable.ic_play_arrow_white);
}
@Override
public void onCompleted() {
super.onCompleted();
updateNotification(R.drawable.ic_replay_white);
showAndAnimateControl(R.drawable.ic_replay_white, false);
}
}
private class MySimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener implements View.OnTouchListener {
private int initialPopupX, initialPopupY;
private boolean isMoving;
@Override
public boolean onDoubleTap(MotionEvent e) {
if (DEBUG) Log.d(TAG, "onDoubleTap() called with: e = [" + e + "]" + "rawXy = " + e.getRawX() + ", " + e.getRawY() + ", xy = " + e.getX() + ", " + e.getY());
if (!playerImpl.isPlaying()) return false;
if (e.getX() > popupWidth / 2) playerImpl.onFastForward();
else playerImpl.onFastRewind();
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (DEBUG) Log.d(TAG, "onSingleTapConfirmed() called with: e = [" + e + "]");
if (playerImpl.getPlayer() == null) return false;
playerImpl.onVideoPlayPause();
return true;
}
@Override
public boolean onDown(MotionEvent e) {
if (DEBUG) Log.d(TAG, "onDown() called with: e = [" + e + "]");
initialPopupX = windowLayoutParams.x;
initialPopupY = windowLayoutParams.y;
popupWidth = playerImpl.getRootView().getWidth();
popupHeight = playerImpl.getRootView().getHeight();
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (!isMoving || playerImpl.getControlsRoot().getAlpha() != 1f) playerImpl.animateView(playerImpl.getControlsRoot(), true, 30, 0);
isMoving = true;
float diffX = (int) (e2.getRawX() - e1.getRawX()), posX = (int) (initialPopupX + diffX);
float diffY = (int) (e2.getRawY() - e1.getRawY()), posY = (int) (initialPopupY + diffY);
if (posX > (screenWidth - popupWidth)) posX = (int) (screenWidth - popupWidth);
else if (posX < 0) posX = 0;
if (posY > (screenHeight - popupHeight)) posY = (int) (screenHeight - popupHeight);
else if (posY < 0) posY = 0;
windowLayoutParams.x = (int) posX;
windowLayoutParams.y = (int) posY;
//noinspection PointlessBooleanExpression
if (DEBUG && false) Log.d(TAG, "PopupVideoPlayer.onScroll = " +
", e1.getRaw = [" + e1.getRawX() + ", " + e1.getRawY() + "]" +
", e2.getRaw = [" + e2.getRawX() + ", " + e2.getRawY() + "]" +
", distanceXy = [" + distanceX + ", " + distanceY + "]" +
", posXy = [" + posX + ", " + posY + "]" +
", popupWh rootView.get wh = [" + popupWidth + " x " + popupHeight + "]");
windowManager.updateViewLayout(playerImpl.getRootView(), windowLayoutParams);
return true;
}
private void onScrollEnd() {
if (DEBUG) Log.d(TAG, "onScrollEnd() called");
if (playerImpl.isControlsVisible() && playerImpl.getCurrentState() == BasePlayer.STATE_PLAYING) {
playerImpl.animateView(playerImpl.getControlsRoot(), false, 300, VideoPlayer.DEFAULT_CONTROLS_HIDE_TIME);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP && isMoving) {
isMoving = false;
onScrollEnd();
}
return true;
}
}
/**
* Fetcher used if open by a link out of NewPipe
*/
private class FetcherRunnable implements StreamExtractorWorker.OnStreamInfoReceivedListener {
private final Context context;
private final Handler mainHandler;
FetcherRunnable(Context context) {
this.mainHandler = new Handler(PopupVideoPlayer.this.getMainLooper());
this.context = context;
}
@Override
public void onReceive(StreamInfo info) {
playerImpl.setVideoTitle(info.title);
playerImpl.setVideoUrl(info.webpage_url);
playerImpl.setVideoThumbnailUrl(info.thumbnail_url);
playerImpl.setChannelName(info.uploader);
playerImpl.setVideoStreamsList(Utils.getSortedStreamVideosList(context, info.video_streams, info.video_only_streams, false));
playerImpl.setAudioStream(Utils.getHighestQualityAudio(info.audio_streams));
int defaultResolution = Utils.getPopupDefaultResolution(context, playerImpl.getVideoStreamsList());
playerImpl.setSelectedIndexStream(defaultResolution);
if (DEBUG) {
Log.d(TAG, "FetcherRunnable.StreamExtractor: chosen = "
+ MediaFormat.getNameById(info.video_streams.get(defaultResolution).format) + " "
+ info.video_streams.get(defaultResolution).resolution + " > "
+ info.video_streams.get(defaultResolution).url);
}
if (info.start_position > 0) playerImpl.setVideoStartPos(info.start_position * 1000);
else playerImpl.setVideoStartPos(-1);
mainHandler.post(new Runnable() {
@Override
public void run() {
playerImpl.play(true);
}
});
imageLoader.resume();
imageLoader.loadImage(info.thumbnail_url, displayImageOptions, new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
mainHandler.post(new Runnable() {
@Override
public void run() {
playerImpl.setVideoThumbnail(loadedImage);
if (loadedImage != null) notRemoteView.setImageViewBitmap(R.id.notificationCover, loadedImage);
updateNotification(-1);
}
});
}
});
}
@Override
public void onError(final int messageId) {
mainHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, messageId, Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
@Override
public void onReCaptchaException() {
mainHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, R.string.recaptcha_request_toast, Toast.LENGTH_LONG).show();
}
});
// Starting ReCaptcha Challenge Activity
Intent intent = new Intent(context, ReCaptchaActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
stopSelf();
}
@Override
public void onBlockedByGemaError() {
mainHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, R.string.blocked_by_gema, Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
@Override
public void onContentErrorWithMessage(final int messageId) {
mainHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, messageId, Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
@Override
public void onContentError() {
mainHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, R.string.content_not_available, Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
@Override
public void onUnrecoverableError(Exception exception) {
exception.printStackTrace();
stopSelf();
}
}
}

View File

@@ -0,0 +1,778 @@
package org.schabi.newpipe.player;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MergingMediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.MediaFormat;
import org.schabi.newpipe.extractor.stream_info.AudioStream;
import org.schabi.newpipe.extractor.stream_info.VideoStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* Base for <b>video</b> players
*
* @author mauriciocolli
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public abstract class VideoPlayer extends BasePlayer implements SimpleExoPlayer.VideoListener, SeekBar.OnSeekBarChangeListener, View.OnClickListener, ExoPlayer.EventListener, PopupMenu.OnMenuItemClickListener, PopupMenu.OnDismissListener {
public static final boolean DEBUG = BasePlayer.DEBUG;
public final String TAG;
/*//////////////////////////////////////////////////////////////////////////
// Intent
//////////////////////////////////////////////////////////////////////////*/
public static final String VIDEO_STREAMS_LIST = "video_streams_list";
public static final String VIDEO_ONLY_AUDIO_STREAM = "video_only_audio_stream";
public static final String INDEX_SEL_VIDEO_STREAM = "index_selected_video_stream";
public static final String STARTED_FROM_NEWPIPE = "started_from_newpipe";
private int selectedIndexStream;
private ArrayList<VideoStream> videoStreamsList = new ArrayList<>();
private AudioStream videoOnlyAudioStream;
/*//////////////////////////////////////////////////////////////////////////
// Player
//////////////////////////////////////////////////////////////////////////*/
public static final int DEFAULT_CONTROLS_HIDE_TIME = 3000; // 3 Seconds
private boolean startedFromNewPipe = true;
private boolean wasPlaying = false;
/*//////////////////////////////////////////////////////////////////////////
// Views
//////////////////////////////////////////////////////////////////////////*/
private View rootView;
private AspectRatioFrameLayout aspectRatioFrameLayout;
private SurfaceView surfaceView;
private View surfaceForeground;
private View loadingPanel;
private ImageView endScreen;
private ImageView controlAnimationView;
private View controlsRoot;
private TextView currentDisplaySeek;
private View bottomControlsRoot;
private SeekBar playbackSeekBar;
private TextView playbackCurrentTime;
private TextView playbackEndTime;
private View topControlsRoot;
private TextView qualityTextView;
private ImageButton fullScreenButton;
private ValueAnimator controlViewAnimator;
private boolean isQualityPopupMenuVisible = false;
private boolean qualityChanged = false;
private int qualityPopupMenuGroupId = 69;
private PopupMenu qualityPopupMenu;
///////////////////////////////////////////////////////////////////////////
public VideoPlayer(String debugTag, Context context) {
super(context);
this.TAG = debugTag;
this.context = context;
}
public void setup(View rootView) {
initViews(rootView);
setup();
}
public void initViews(View rootView) {
this.rootView = rootView;
this.aspectRatioFrameLayout = (AspectRatioFrameLayout) rootView.findViewById(R.id.aspectRatioLayout);
this.surfaceView = (SurfaceView) rootView.findViewById(R.id.surfaceView);
this.surfaceForeground = rootView.findViewById(R.id.surfaceForeground);
this.loadingPanel = rootView.findViewById(R.id.loadingPanel);
this.endScreen = (ImageView) rootView.findViewById(R.id.endScreen);
this.controlAnimationView = (ImageView) rootView.findViewById(R.id.controlAnimationView);
this.controlsRoot = rootView.findViewById(R.id.playbackControlRoot);
this.currentDisplaySeek = (TextView) rootView.findViewById(R.id.currentDisplaySeek);
this.playbackSeekBar = (SeekBar) rootView.findViewById(R.id.playbackSeekBar);
this.playbackCurrentTime = (TextView) rootView.findViewById(R.id.playbackCurrentTime);
this.playbackEndTime = (TextView) rootView.findViewById(R.id.playbackEndTime);
this.bottomControlsRoot = rootView.findViewById(R.id.bottomControls);
this.topControlsRoot = rootView.findViewById(R.id.topControls);
this.qualityTextView = (TextView) rootView.findViewById(R.id.qualityTextView);
this.fullScreenButton = (ImageButton) rootView.findViewById(R.id.fullScreenButton);
//this.aspectRatioFrameLayout.setAspectRatio(16.0f / 9.0f);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) playbackSeekBar.getThumb().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
this.playbackSeekBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
this.qualityPopupMenu = new PopupMenu(context, qualityTextView);
((ProgressBar) this.loadingPanel.findViewById(R.id.progressBarLoadingPanel)).getIndeterminateDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
}
@Override
public void initListeners() {
super.initListeners();
playbackSeekBar.setOnSeekBarChangeListener(this);
fullScreenButton.setOnClickListener(this);
qualityTextView.setOnClickListener(this);
}
@Override
public void initPlayer() {
super.initPlayer();
simpleExoPlayer.setVideoSurfaceView(surfaceView);
simpleExoPlayer.setVideoListener(this);
}
@SuppressWarnings("unchecked")
public void handleIntent(Intent intent) {
super.handleIntent(intent);
if (DEBUG) Log.d(TAG, "handleIntent() called with: intent = [" + intent + "]");
if (intent == null) return;
selectedIndexStream = intent.getIntExtra(INDEX_SEL_VIDEO_STREAM, -1);
Serializable serializable = intent.getSerializableExtra(VIDEO_STREAMS_LIST);
if (serializable instanceof ArrayList) videoStreamsList = (ArrayList<VideoStream>) serializable;
if (serializable instanceof Vector) videoStreamsList = new ArrayList<>((List<VideoStream>) serializable);
Serializable audioStream = intent.getSerializableExtra(VIDEO_ONLY_AUDIO_STREAM);
if (audioStream != null) videoOnlyAudioStream = (AudioStream) audioStream;
startedFromNewPipe = intent.getBooleanExtra(STARTED_FROM_NEWPIPE, true);
play(true);
}
public void play(boolean autoPlay) {
playUrl(getSelectedVideoStream().url, MediaFormat.getSuffixById(getSelectedVideoStream().format), autoPlay);
}
@Override
public void playUrl(String url, String format, boolean autoPlay) {
if (DEBUG) Log.d(TAG, "play() called with: url = [" + url + "], autoPlay = [" + autoPlay + "]");
qualityChanged = false;
if (url == null || simpleExoPlayer == null) {
RuntimeException runtimeException = new RuntimeException((url == null ? "Url " : "Player ") + " null");
onError(runtimeException);
throw runtimeException;
}
qualityPopupMenu.getMenu().removeGroup(qualityPopupMenuGroupId);
buildQualityMenu(qualityPopupMenu);
super.playUrl(url, format, autoPlay);
}
@Override
public MediaSource buildMediaSource(String url, String overrideExtension) {
MediaSource mediaSource = super.buildMediaSource(url, overrideExtension);
if (!getSelectedVideoStream().isVideoOnly) return mediaSource;
Uri audioUri = Uri.parse(videoOnlyAudioStream.url);
return new MergingMediaSource(mediaSource, new ExtractorMediaSource(audioUri, cacheDataSourceFactory, extractorsFactory, null, null));
}
public void buildQualityMenu(PopupMenu popupMenu) {
for (int i = 0; i < videoStreamsList.size(); i++) {
VideoStream videoStream = videoStreamsList.get(i);
popupMenu.getMenu().add(qualityPopupMenuGroupId, i, Menu.NONE, MediaFormat.getNameById(videoStream.format) + " " + videoStream.resolution);
}
qualityTextView.setText(getSelectedVideoStream().resolution);
popupMenu.setOnMenuItemClickListener(this);
popupMenu.setOnDismissListener(this);
}
/*//////////////////////////////////////////////////////////////////////////
// States Implementation
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onLoading() {
if (DEBUG) Log.d(TAG, "onLoading() called");
if (!isProgressLoopRunning.get()) startProgressLoop();
showAndAnimateControl(-1, true);
playbackSeekBar.setEnabled(true);
playbackSeekBar.setProgress(0);
// Bug on lower api, disabling and enabling the seekBar resets the thumb color -.-, so sets the color again
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) playbackSeekBar.getThumb().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
animateView(endScreen, false, 0, 0);
loadingPanel.setBackgroundColor(Color.BLACK);
animateView(loadingPanel, true, 0, 0);
animateView(surfaceForeground, true, 100, 0);
}
@Override
public void onPlaying() {
if (DEBUG) Log.d(TAG, "onPlaying() called");
if (!isProgressLoopRunning.get()) startProgressLoop();
showAndAnimateControl(-1, true);
loadingPanel.setVisibility(View.GONE);
animateView(controlsRoot, true, 500, 0, new Runnable() {
@Override
public void run() {
animateView(controlsRoot, false, 500, DEFAULT_CONTROLS_HIDE_TIME, true);
}
});
animateView(currentDisplaySeek, false, 200, 0);
}
@Override
public void onBuffering() {
if (DEBUG) Log.d(TAG, "onBuffering() called");
loadingPanel.setBackgroundColor(Color.TRANSPARENT);
animateView(loadingPanel, true, 500, 0);
}
@Override
public void onPaused() {
if (DEBUG) Log.d(TAG, "onPaused() called");
animateView(controlsRoot, true, 500, 100);
loadingPanel.setVisibility(View.GONE);
}
@Override
public void onPausedSeek() {
if (DEBUG) Log.d(TAG, "onPausedSeek() called");
showAndAnimateControl(-1, true);
}
@Override
public void onCompleted() {
if (DEBUG) Log.d(TAG, "onCompleted() called");
if (isProgressLoopRunning.get()) stopProgressLoop();
animateView(controlsRoot, true, 500, 0);
animateView(endScreen, true, 800, 0);
animateView(currentDisplaySeek, false, 200, 0);
loadingPanel.setVisibility(View.GONE);
playbackSeekBar.setMax((int) simpleExoPlayer.getDuration());
playbackSeekBar.setProgress(playbackSeekBar.getMax());
playbackSeekBar.setEnabled(false);
playbackEndTime.setText(getTimeString(playbackSeekBar.getMax()));
playbackCurrentTime.setText(playbackEndTime.getText());
// Bug on lower api, disabling and enabling the seekBar resets the thumb color -.-, so sets the color again
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) playbackSeekBar.getThumb().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
animateView(surfaceForeground, true, 100, 0);
if (currentRepeatMode == RepeatMode.REPEAT_ONE) {
changeState(STATE_LOADING);
simpleExoPlayer.seekTo(0);
}
}
/*//////////////////////////////////////////////////////////////////////////
// ExoPlayer Video Listener
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
if (DEBUG) {
Log.d(TAG, "onVideoSizeChanged() called with: width / height = [" + width + " / " + height + " = " + (((float) width) / height) + "], unappliedRotationDegrees = [" + unappliedRotationDegrees + "], pixelWidthHeightRatio = [" + pixelWidthHeightRatio + "]");
}
aspectRatioFrameLayout.setAspectRatio(((float) width) / height);
}
@Override
public void onRenderedFirstFrame() {
animateView(surfaceForeground, false, 100, 0);
}
/*//////////////////////////////////////////////////////////////////////////
// General Player
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onPrepared(boolean playWhenReady) {
if (DEBUG) Log.d(TAG, "onPrepared() called with: playWhenReady = [" + playWhenReady + "]");
if (videoStartPos > 0) {
playbackSeekBar.setProgress(videoStartPos);
playbackCurrentTime.setText(getTimeString(videoStartPos));
videoStartPos = -1;
}
playbackSeekBar.setMax((int) simpleExoPlayer.getDuration());
playbackEndTime.setText(getTimeString((int) simpleExoPlayer.getDuration()));
super.onPrepared(playWhenReady);
}
@Override
public void destroy() {
super.destroy();
if (endScreen != null) endScreen.setImageBitmap(null);
}
@Override
public void onUpdateProgress(int currentProgress, int duration, int bufferPercent) {
if (!isPrepared) return;
if (currentState != STATE_PAUSED) {
if (currentState != STATE_PAUSED_SEEK) playbackSeekBar.setProgress(currentProgress);
playbackCurrentTime.setText(getTimeString(currentProgress));
}
if (simpleExoPlayer.isLoading() || bufferPercent > 90) {
playbackSeekBar.setSecondaryProgress((int) (playbackSeekBar.getMax() * ((float) bufferPercent / 100)));
}
if (DEBUG && bufferPercent % 20 == 0) { //Limit log
Log.d(TAG, "updateProgress() called with: isVisible = " + isControlsVisible() + ", currentProgress = [" + currentProgress + "], duration = [" + duration + "], bufferPercent = [" + bufferPercent + "]");
}
}
@Override
public void onVideoPlayPauseRepeat() {
if (DEBUG) Log.d(TAG, "onVideoPlayPauseRepeat() called");
if (qualityChanged) {
setVideoStartPos(0);
play(true);
} else super.onVideoPlayPauseRepeat();
}
@Override
public void onThumbnailReceived(Bitmap thumbnail) {
super.onThumbnailReceived(thumbnail);
if (thumbnail != null) endScreen.setImageBitmap(thumbnail);
}
protected abstract void onFullScreenButtonClicked();
@Override
public void onFastRewind() {
super.onFastRewind();
showAndAnimateControl(R.drawable.ic_action_av_fast_rewind, true);
}
@Override
public void onFastForward() {
super.onFastForward();
showAndAnimateControl(R.drawable.ic_action_av_fast_forward, true);
}
/*//////////////////////////////////////////////////////////////////////////
// OnClick related
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onClick(View v) {
if (DEBUG) Log.d(TAG, "onClick() called with: v = [" + v + "]");
if (v.getId() == fullScreenButton.getId()) {
onFullScreenButtonClicked();
} else if (v.getId() == qualityTextView.getId()) {
onQualitySelectorClicked();
}
}
/**
* Called when an item of the quality selector is selected
*/
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (DEBUG) Log.d(TAG, "onMenuItemClick() called with: menuItem = [" + menuItem + "], menuItem.getItemId = [" + menuItem.getItemId() + "]");
if (selectedIndexStream == menuItem.getItemId()) return true;
setVideoStartPos((int) simpleExoPlayer.getCurrentPosition());
selectedIndexStream = menuItem.getItemId();
if (!(getCurrentState() == STATE_COMPLETED)) play(wasPlaying);
else qualityChanged = true;
qualityTextView.setText(menuItem.getTitle());
return true;
}
/**
* Called when the quality selector is dismissed
*/
@Override
public void onDismiss(PopupMenu menu) {
if (DEBUG) Log.d(TAG, "onDismiss() called with: menu = [" + menu + "]");
isQualityPopupMenuVisible = false;
qualityTextView.setText(getSelectedVideoStream().resolution);
}
public void onQualitySelectorClicked() {
if (DEBUG) Log.d(TAG, "onQualitySelectorClicked() called");
qualityPopupMenu.show();
isQualityPopupMenuVisible = true;
animateView(getControlsRoot(), true, 300, 0);
VideoStream videoStream = getSelectedVideoStream();
qualityTextView.setText(MediaFormat.getNameById(videoStream.format) + " " + videoStream.resolution);
wasPlaying = isPlaying();
}
/*//////////////////////////////////////////////////////////////////////////
// SeekBar Listener
//////////////////////////////////////////////////////////////////////////*/
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (DEBUG && fromUser) Log.d(TAG, "onProgressChanged() called with: seekBar = [" + seekBar + "], progress = [" + progress + "]");
//if (fromUser) playbackCurrentTime.setText(getTimeString(progress));
if (fromUser) currentDisplaySeek.setText(getTimeString(progress));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (DEBUG) Log.d(TAG, "onStartTrackingTouch() called with: seekBar = [" + seekBar + "]");
if (getCurrentState() != STATE_PAUSED_SEEK) changeState(STATE_PAUSED_SEEK);
wasPlaying = isPlaying();
if (isPlaying()) simpleExoPlayer.setPlayWhenReady(false);
animateView(controlsRoot, true, 0, 0);
animateView(currentDisplaySeek, true, 300, 0);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (DEBUG) Log.d(TAG, "onStopTrackingTouch() called with: seekBar = [" + seekBar + "]");
simpleExoPlayer.seekTo(seekBar.getProgress());
if (wasPlaying || simpleExoPlayer.getDuration() == seekBar.getProgress()) simpleExoPlayer.setPlayWhenReady(true);
playbackCurrentTime.setText(getTimeString(seekBar.getProgress()));
animateView(currentDisplaySeek, false, 200, 0);
if (getCurrentState() == STATE_PAUSED_SEEK) changeState(STATE_BUFFERING);
if (!isProgressLoopRunning.get()) startProgressLoop();
}
/*//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////*/
public boolean isControlsVisible() {
return controlsRoot != null && controlsRoot.getVisibility() == View.VISIBLE;
}
/**
* Show a animation, and depending on goneOnEnd, will stay on the screen or be gone
*
* @param drawableId the drawable that will be used to animate, pass -1 to clear any animation that is visible
* @param goneOnEnd will set the animation view to GONE on the end of the animation
*/
public void showAndAnimateControl(final int drawableId, final boolean goneOnEnd) {
if (DEBUG) Log.d(TAG, "showAndAnimateControl() called with: drawableId = [" + drawableId + "], goneOnEnd = [" + goneOnEnd + "]");
if (controlViewAnimator != null && controlViewAnimator.isRunning()) {
if (DEBUG) Log.d(TAG, "showAndAnimateControl: controlViewAnimator.isRunning");
controlViewAnimator.end();
}
if (drawableId == -1) {
if (controlAnimationView.getVisibility() == View.VISIBLE) {
controlViewAnimator = ObjectAnimator.ofPropertyValuesHolder(controlAnimationView,
PropertyValuesHolder.ofFloat(View.ALPHA, 1f, 0f),
PropertyValuesHolder.ofFloat(View.SCALE_X, 1.4f, 1f),
PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.4f, 1f)
).setDuration(300);
controlViewAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
controlAnimationView.setVisibility(View.GONE);
}
});
controlViewAnimator.start();
}
return;
}
float scaleFrom = goneOnEnd ? 1f : 1f, scaleTo = goneOnEnd ? 1.8f : 1.4f;
float alphaFrom = goneOnEnd ? 1f : 0f, alphaTo = goneOnEnd ? 0f : 1f;
controlViewAnimator = ObjectAnimator.ofPropertyValuesHolder(controlAnimationView,
PropertyValuesHolder.ofFloat(View.ALPHA, alphaFrom, alphaTo),
PropertyValuesHolder.ofFloat(View.SCALE_X, scaleFrom, scaleTo),
PropertyValuesHolder.ofFloat(View.SCALE_Y, scaleFrom, scaleTo)
);
controlViewAnimator.setDuration(goneOnEnd ? 1000 : 500);
controlViewAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (goneOnEnd) controlAnimationView.setVisibility(View.GONE);
else controlAnimationView.setVisibility(View.VISIBLE);
}
});
controlAnimationView.setVisibility(View.VISIBLE);
controlAnimationView.setImageDrawable(ContextCompat.getDrawable(context, drawableId));
controlViewAnimator.start();
}
public void animateView(View view, boolean enterOrExit, long duration, long delay) {
animateView(view, enterOrExit, duration, delay, null, false);
}
public void animateView(View view, boolean enterOrExit, long duration, long delay, boolean hideUi) {
animateView(view, enterOrExit, duration, delay, null, hideUi);
}
public void animateView(final View view, final boolean enterOrExit, long duration, long delay, final Runnable execOnEnd) {
animateView(view, enterOrExit, duration, delay, execOnEnd, false);
}
/**
* Animate the view
*
* @param view view that will be animated
* @param enterOrExit true to enter, false to exit
* @param duration how long the animation will take, in milliseconds
* @param delay how long the animation will wait to start, in milliseconds
* @param execOnEnd runnable that will be executed when the animation ends
* @param hideUi need to hide ui when animation ends,
* just a helper for classes extending this
*/
public void animateView(final View view, final boolean enterOrExit, long duration, long delay, final Runnable execOnEnd, boolean hideUi) {
if (DEBUG) {
Log.d(TAG, "animateView() called with: view = [" + view + "], enterOrExit = [" + enterOrExit + "], duration = [" + duration + "], delay = [" + delay + "], execOnEnd = [" + execOnEnd + "]");
}
if (view.getVisibility() == View.VISIBLE && enterOrExit) {
if (DEBUG) Log.d(TAG, "animateView() view was already visible > view = [" + view + "]");
view.animate().setListener(null).cancel();
view.setVisibility(View.VISIBLE);
view.setAlpha(1f);
if (execOnEnd != null) execOnEnd.run();
return;
} else if ((view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE) && !enterOrExit) {
if (DEBUG) Log.d(TAG, "animateView() view was already gone > view = [" + view + "]");
view.animate().setListener(null).cancel();
view.setVisibility(View.GONE);
view.setAlpha(0f);
if (execOnEnd != null) execOnEnd.run();
return;
}
view.animate().setListener(null).cancel();
view.setVisibility(View.VISIBLE);
if (view == controlsRoot) {
if (enterOrExit) {
view.animate().alpha(1f).setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (execOnEnd != null) execOnEnd.run();
}
}).start();
} else {
view.animate().alpha(0f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) execOnEnd.run();
}
})
.start();
}
return;
}
if (enterOrExit) {
view.setAlpha(0f);
view.setScaleX(.8f);
view.setScaleY(.8f);
view.animate().alpha(1f).scaleX(1f).scaleY(1f).setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (execOnEnd != null) execOnEnd.run();
}
}).start();
} else {
view.setAlpha(1f);
view.setScaleX(1f);
view.setScaleY(1f);
view.animate().alpha(0f).scaleX(.8f).scaleY(.8f).setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) execOnEnd.run();
}
})
.start();
}
}
public boolean isQualityMenuVisible() {
return isQualityPopupMenuVisible;
}
/*//////////////////////////////////////////////////////////////////////////
// Getters and Setters
//////////////////////////////////////////////////////////////////////////*/
public AspectRatioFrameLayout getAspectRatioFrameLayout() {
return aspectRatioFrameLayout;
}
public SurfaceView getSurfaceView() {
return surfaceView;
}
public boolean wasPlaying() {
return wasPlaying;
}
public VideoStream getSelectedVideoStream() {
return videoStreamsList.get(selectedIndexStream);
}
public Uri getSelectedStreamUri() {
return Uri.parse(getSelectedVideoStream().url);
}
public int getQualityPopupMenuGroupId() {
return qualityPopupMenuGroupId;
}
public int getSelectedStreamIndex() {
return selectedIndexStream;
}
public void setSelectedIndexStream(int selectedIndexStream) {
this.selectedIndexStream = selectedIndexStream;
}
public void setAudioStream(AudioStream audioStream) {
this.videoOnlyAudioStream = audioStream;
}
public AudioStream getAudioStream() {
return videoOnlyAudioStream;
}
public ArrayList<VideoStream> getVideoStreamsList() {
return videoStreamsList;
}
public void setVideoStreamsList(ArrayList<VideoStream> videoStreamsList) {
this.videoStreamsList = videoStreamsList;
}
public boolean isStartedFromNewPipe() {
return startedFromNewPipe;
}
public void setStartedFromNewPipe(boolean startedFromNewPipe) {
this.startedFromNewPipe = startedFromNewPipe;
}
public View getRootView() {
return rootView;
}
public void setRootView(View rootView) {
this.rootView = rootView;
}
public View getLoadingPanel() {
return loadingPanel;
}
public ImageView getEndScreen() {
return endScreen;
}
public ImageView getControlAnimationView() {
return controlAnimationView;
}
public View getControlsRoot() {
return controlsRoot;
}
public View getBottomControlsRoot() {
return bottomControlsRoot;
}
public SeekBar getPlaybackSeekBar() {
return playbackSeekBar;
}
public TextView getPlaybackCurrentTime() {
return playbackCurrentTime;
}
public TextView getPlaybackEndTime() {
return playbackEndTime;
}
public View getTopControlsRoot() {
return topControlsRoot;
}
public TextView getQualityTextView() {
return qualityTextView;
}
public ImageButton getFullScreenButton() {
return fullScreenButton;
}
public PopupMenu getQualityPopupMenu() {
return qualityPopupMenu;
}
public View getSurfaceForeground() {
return surfaceForeground;
}
public TextView getCurrentDisplaySeek() {
return currentDisplaySeek;
}
}

View File

@@ -1,10 +1,17 @@
package org.schabi.newpipe.extractor;
package org.schabi.newpipe.report;
import android.graphics.Bitmap;
import android.content.Context;
import org.acra.collector.CrashReportData;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;
import org.schabi.newpipe.R;
/**
* Created by Christian Schabesberger on 13.09.16.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* AbstractVideoInfo.java is part of NewPipe.
* AcraReportSender.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,14 +27,12 @@ import android.graphics.Bitmap;
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
/**Common properties between VideoInfo and VideoPreviewInfo.*/
public abstract class AbstractVideoInfo {
public String id = "";
public String title = "";
public String uploader = "";
public String thumbnail_url = "";
public Bitmap thumbnail = null;
public String webpage_url = "";
public String upload_date = "";
public long view_count = -1;
public class AcraReportSender implements ReportSender {
@Override
public void send(Context context, CrashReportData report) throws ReportSenderException {
ErrorActivity.reportError(context, report,
ErrorActivity.ErrorInfo.make(ErrorActivity.UI_ERROR,"none",
"App crash, UI failure", R.string.app_ui_crash));
}
}

View File

@@ -1,12 +1,17 @@
package org.schabi.newpipe.extractor;
package org.schabi.newpipe.report;
import java.io.IOException;
import android.content.Context;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderFactory;
import org.schabi.newpipe.report.AcraReportSender;
/**
* Created by Christian Schabesberger on 23.08.15.
* Created by Christian Schabesberger on 13.09.16.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* StreamingService.java is part of NewPipe.
* AcraReportSenderFactory.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -22,16 +27,8 @@ import java.io.IOException;
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public interface StreamingService {
class ServiceInfo {
public String name = "";
public class AcraReportSenderFactory implements ReportSenderFactory {
public ReportSender create(Context context, ACRAConfiguration config) {
return new AcraReportSender();
}
ServiceInfo getServiceInfo();
StreamExtractor getExtractorInstance(String url, Downloader downloader)
throws IOException, ExctractionException;
SearchEngine getSearchEngineInstance();
VideoUrlIdHandler getUrlIdHandler();
}

View File

@@ -0,0 +1,518 @@
package org.schabi.newpipe.report;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.acra.ReportField;
import org.acra.collector.CrashReportData;
import org.json.JSONArray;
import org.json.JSONObject;
import org.schabi.newpipe.ActivityCommunicator;
import org.schabi.newpipe.BuildConfig;
import org.schabi.newpipe.Downloader;
import org.schabi.newpipe.MainActivity;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.Parser;
import org.schabi.newpipe.util.ThemeHelper;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Vector;
/**
* Created by Christian Schabesberger on 24.10.15.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* ErrorActivity.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class ErrorActivity extends AppCompatActivity {
// LOG TAGS
public static final String TAG = ErrorActivity.class.toString();
// BUNDLE TAGS
public static final String ERROR_INFO = "error_info";
public static final String ERROR_LIST = "error_list";
// MESSAGE ID
public static final int SEARCHED = 0;
public static final int REQUESTED_STREAM = 1;
public static final int GET_SUGGESTIONS = 2;
public static final int SOMETHING_ELSE = 3;
public static final int USER_REPORT = 4;
public static final int LOAD_IMAGE = 5;
public static final int UI_ERROR = 6;
public static final int REQUESTED_CHANNEL = 7;
// MESSAGE STRING
public static final String SEARCHED_STRING = "searched";
public static final String REQUESTED_STREAM_STRING = "requested stream";
public static final String GET_SUGGESTIONS_STRING = "get suggestions";
public static final String SOMETHING_ELSE_STRING = "something";
public static final String USER_REPORT_STRING = "user report";
public static final String LOAD_IMAGE_STRING = "load image";
public static final String UI_ERROR_STRING = "ui error";
public static final String REQUESTED_CHANNEL_STRING = "requested channel";
public static final String ERROR_EMAIL_ADDRESS = "crashreport@newpipe.schabi.org";
public static final String ERROR_EMAIL_SUBJECT = "Exception in NewPipe " + BuildConfig.VERSION_NAME;
Thread globIpRangeThread;
private String[] errorList;
private ErrorInfo errorInfo;
private Class returnActivity;
private String currentTimeStamp;
private String globIpRange;
// views
private TextView errorView;
private EditText userCommentBox;
private Button reportButton;
private TextView infoView;
private TextView errorMessageView;
public static void reportUiError(final AppCompatActivity activity, final Throwable el) {
reportError(activity, el, activity.getClass(), null, ErrorInfo.make(UI_ERROR, "none", "", R.string.app_ui_crash));
}
public static void reportError(final Context context, final List<Throwable> el,
final Class returnAcitivty, View rootView, final ErrorInfo errorInfo) {
if (rootView != null) {
Snackbar.make(rootView, R.string.error_snackbar_message, Snackbar.LENGTH_LONG)
.setActionTextColor(Color.YELLOW)
.setAction(R.string.error_snackbar_action, new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCommunicator ac = ActivityCommunicator.getCommunicator();
ac.returnActivity = returnAcitivty;
Intent intent = new Intent(context, ErrorActivity.class);
intent.putExtra(ERROR_INFO, errorInfo);
intent.putExtra(ERROR_LIST, elToSl(el));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}).show();
} else {
ActivityCommunicator ac = ActivityCommunicator.getCommunicator();
ac.returnActivity = returnAcitivty;
Intent intent = new Intent(context, ErrorActivity.class);
intent.putExtra(ERROR_INFO, errorInfo);
intent.putExtra(ERROR_LIST, elToSl(el));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
public static void reportError(final Context context, final Throwable e,
final Class returnAcitivty, View rootView, final ErrorInfo errorInfo) {
List<Throwable> el = null;
if(e != null) {
el = new Vector<>();
el.add(e);
}
reportError(context, el, returnAcitivty, rootView, errorInfo);
}
// async call
public static void reportError(Handler handler, final Context context, final Throwable e,
final Class returnAcitivty, final View rootView, final ErrorInfo errorInfo) {
List<Throwable> el = null;
if(e != null) {
el = new Vector<>();
el.add(e);
}
reportError(handler, context, el, returnAcitivty, rootView, errorInfo);
}
// async call
public static void reportError(Handler handler, final Context context, final List<Throwable> el,
final Class returnAcitivty, final View rootView, final ErrorInfo errorInfo) {
handler.post(new Runnable() {
@Override
public void run() {
reportError(context, el, returnAcitivty, rootView, errorInfo);
}
});
}
public static void reportError(final Context context, final CrashReportData report, final ErrorInfo errorInfo) {
// get key first (don't ask about this solution)
ReportField key = null;
for(ReportField k : report.keySet()) {
if(k.toString().equals("STACK_TRACE")) {
key = k;
}
}
String[] el = new String[] { report.get(key) };
Intent intent = new Intent(context, ErrorActivity.class);
intent.putExtra(ERROR_INFO, errorInfo);
intent.putExtra(ERROR_LIST, el);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
private static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
// errorList to StringList
private static String[] elToSl(List<Throwable> stackTraces) {
String[] out = new String[stackTraces.size()];
for (int i = 0; i < stackTraces.size(); i++) {
out[i] = getStackTrace(stackTraces.get(i));
}
return out;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeHelper.setTheme(this, true);
setContentView(R.layout.activity_error);
Intent intent = getIntent();
try {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.error_report_title);
actionBar.setDisplayShowTitleEnabled(true);
} catch (Throwable e) {
Log.e(TAG, "Error turing exception handling");
e.printStackTrace();
}
reportButton = (Button) findViewById(R.id.errorReportButton);
userCommentBox = (EditText) findViewById(R.id.errorCommentBox);
errorView = (TextView) findViewById(R.id.errorView);
infoView = (TextView) findViewById(R.id.errorInfosView);
errorMessageView = (TextView) findViewById(R.id.errorMessageView);
ActivityCommunicator ac = ActivityCommunicator.getCommunicator();
returnActivity = ac.returnActivity;
errorInfo = intent.getParcelableExtra(ERROR_INFO);
errorList = intent.getStringArrayExtra(ERROR_LIST);
//importand add gurumeditaion
addGuruMeditaion();
currentTimeStamp = getCurrentTimeStamp();
reportButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:" + ERROR_EMAIL_ADDRESS))
.putExtra(Intent.EXTRA_SUBJECT, ERROR_EMAIL_SUBJECT)
.putExtra(Intent.EXTRA_TEXT, buildJson());
startActivity(Intent.createChooser(intent, "Send Email"));
}
});
reportButton.setEnabled(false);
globIpRangeThread = new Thread(new IpRagneRequester());
globIpRangeThread.start();
// normal bugreport
buildInfo(errorInfo);
if(errorInfo.message != 0) {
errorMessageView.setText(errorInfo.message);
} else {
errorMessageView.setVisibility(View.GONE);
findViewById(R.id.messageWhatHappenedView).setVisibility(View.GONE);
}
errorView.setText(formErrorText(errorList));
//print stack trace once again for debugging:
for(String e : errorList) {
Log.e(TAG, e);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.error_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
goToReturnActivity();
break;
case R.id.menu_item_share_error: {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, buildJson());
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, getString(R.string.share_dialog_title)));
}
break;
}
return false;
}
private String formErrorText(String[] el) {
String text = "";
if(el != null) {
for (String e : el) {
text += "-------------------------------------\n"
+ e;
}
}
text += "-------------------------------------";
return text;
}
private void goToReturnActivity() {
if (returnActivity == null) {
super.onBackPressed();
} else {
Intent intent;
if (returnActivity != null &&
returnActivity.isAssignableFrom(Activity.class)) {
intent = new Intent(this, returnActivity);
} else {
intent = new Intent(this, MainActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, intent);
}
}
private void buildInfo(ErrorInfo info) {
TextView infoLabelView = (TextView) findViewById(R.id.errorInfoLabelsView);
TextView infoView = (TextView) findViewById(R.id.errorInfosView);
String text = "";
infoLabelView.setText(getString(R.string.info_labels).replace("\\n", "\n"));
text += getUserActionString(info.userAction)
+ "\n" + info.request
+ "\n" + getContentLangString()
+ "\n" + info.serviceName
+ "\n" + currentTimeStamp
+ "\n" + getPackageName()
+ "\n" + BuildConfig.VERSION_NAME
+ "\n" + getOsString();
infoView.setText(text);
}
private String buildJson() {
JSONObject errorObject = new JSONObject();
try {
errorObject.put("user_action", getUserActionString(errorInfo.userAction))
.put("request", errorInfo.request)
.put("content_language", getContentLangString())
.put("service", errorInfo.serviceName)
.put("package", getPackageName())
.put("version", BuildConfig.VERSION_NAME)
.put("os", getOsString())
.put("time", currentTimeStamp)
.put("ip_range", globIpRange);
JSONArray exceptionArray = new JSONArray();
if(errorList != null) {
for (String e : errorList) {
exceptionArray.put(e);
}
}
errorObject.put("exceptions", exceptionArray);
errorObject.put("user_comment", userCommentBox.getText().toString());
return errorObject.toString(3);
} catch (Throwable e) {
Log.e(TAG, "Error while erroring: Could not build json");
e.printStackTrace();
}
return "";
}
private String getUserActionString(int userAction) {
switch (userAction) {
case REQUESTED_STREAM:
return REQUESTED_STREAM_STRING;
case SEARCHED:
return SEARCHED_STRING;
case GET_SUGGESTIONS:
return GET_SUGGESTIONS_STRING;
case SOMETHING_ELSE:
return SOMETHING_ELSE_STRING;
case USER_REPORT:
return USER_REPORT_STRING;
case LOAD_IMAGE:
return LOAD_IMAGE_STRING;
case UI_ERROR:
return UI_ERROR_STRING;
case REQUESTED_CHANNEL:
return REQUESTED_CHANNEL_STRING;
default:
return "Your description is in another castle.";
}
}
private String getContentLangString() {
return PreferenceManager.getDefaultSharedPreferences(this)
.getString(this.getString(R.string.search_language_key), "none");
}
private String getOsString() {
String osBase = Build.VERSION.SDK_INT >= 23 ? Build.VERSION.BASE_OS : "Android";
return System.getProperty("os.name")
+ " " + (osBase.isEmpty() ? "Android" : osBase)
+ " " + Build.VERSION.RELEASE
+ " - " + Integer.toString(Build.VERSION.SDK_INT);
}
private void addGuruMeditaion() {
//just an easter egg
TextView sorryView = (TextView) findViewById(R.id.errorSorryView);
String text = sorryView.getText().toString();
text += "\n" + getString(R.string.guru_meditation);
sorryView.setText(text);
}
@Override
public void onBackPressed() {
//super.onBackPressed();
goToReturnActivity();
}
public String getCurrentTimeStamp() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df.format(new Date());
}
public static class ErrorInfo implements Parcelable {
public static final Parcelable.Creator<ErrorInfo> CREATOR = new Parcelable.Creator<ErrorInfo>() {
@Override
public ErrorInfo createFromParcel(Parcel source) {
return new ErrorInfo(source);
}
@Override
public ErrorInfo[] newArray(int size) {
return new ErrorInfo[size];
}
};
public int userAction;
public String request;
public String serviceName;
public int message;
public ErrorInfo() {
}
protected ErrorInfo(Parcel in) {
this.userAction = in.readInt();
this.request = in.readString();
this.serviceName = in.readString();
this.message = in.readInt();
}
public static ErrorInfo make(int userAction, String serviceName, String request, int message) {
ErrorInfo info = new ErrorInfo();
info.userAction = userAction;
info.serviceName = serviceName;
info.request = request;
info.message = message;
return info;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.userAction);
dest.writeString(this.request);
dest.writeString(this.serviceName);
dest.writeInt(this.message);
}
}
private class IpRagneRequester implements Runnable {
Handler h = new Handler();
public void run() {
String ipRange = "none";
try {
Downloader dl = Downloader.getInstance();
String ip = dl.download("https://ipv4.icanhazip.com");
ipRange = Parser.matchGroup1("([0-9]*\\.[0-9]*\\.)[0-9]*\\.[0-9]*", ip)
+ "0.0";
} catch(Throwable e) {
Log.d(TAG, "Error while error: could not get iprange");
e.printStackTrace();
} finally {
h.post(new IpRageReturnRunnable(ipRange));
}
}
}
private class IpRageReturnRunnable implements Runnable {
String ipRange;
public IpRageReturnRunnable(String ipRange) {
this.ipRange = ipRange;
}
public void run() {
globIpRange = ipRange;
if(infoView != null) {
String text = infoView.getText().toString();
text += "\n" + globIpRange;
infoView.setText(text);
reportButton.setEnabled(true);
}
}
}
}

View File

@@ -18,39 +18,77 @@
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.schabi.newpipe;
package org.schabi.newpipe.settings;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import org.schabi.newpipe.R;
import java.io.File;
import us.shandian.giga.util.Utility;
/**
* Helper for global settings
*/
/**
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* NewPipeSettings.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class NewPipeSettings {
private NewPipeSettings() {
}
public static void initSettings(Context context) {
PreferenceManager.setDefaultValues(context, R.xml.settings, false);
getVideoDownloadFolder(context);
getAudioDownloadFolder(context);
}
public static File getDownloadFolder() {
return getFolder(Environment.DIRECTORY_DOWNLOADS);
}
public static File getVideoDownloadFolder(Context context) {
return getFolder(context, R.string.download_path_key, Environment.DIRECTORY_MOVIES);
}
public static String getVideoDownloadPath(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final String key = context.getString(R.string.download_path_key);
String downloadPath = prefs.getString(key, Environment.DIRECTORY_MOVIES);
return downloadPath;
}
public static File getAudioDownloadFolder(Context context) {
return getFolder(context, R.string.download_path_audio_key, Environment.DIRECTORY_MUSIC);
}
public static String getAudioDownloadPath(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final String key = context.getString(R.string.download_path_audio_key);
String downloadPath = prefs.getString(key, Environment.DIRECTORY_MUSIC);
return downloadPath;
}
private static File getFolder(Context context, int keyID, String defaultDirectoryName) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final String key = context.getString(keyID);

View File

@@ -0,0 +1,157 @@
package org.schabi.newpipe.settings;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import org.schabi.newpipe.R;
import org.schabi.newpipe.util.ThemeHelper;
/**
* Created by Christian Schabesberger on 31.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* SettingsActivity.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class SettingsActivity extends PreferenceActivity {
SettingsFragment f = new SettingsFragment();
private AppCompatDelegate mDelegate = null;
public static void initSettings(Context context) {
NewPipeSettings.initSettings(context);
}
@Override
protected void onCreate(Bundle savedInstanceBundle) {
ThemeHelper.setTheme(this, true);
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceBundle);
super.onCreate(savedInstanceBundle);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.settings_title);
actionBar.setDisplayShowTitleEnabled(true);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, f)
.commit();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
f.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
private ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
@NonNull
@Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
@Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
@Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home) {
finish();
}
return true;
}
}

View File

@@ -0,0 +1,297 @@
package org.schabi.newpipe.settings;
import android.app.Activity;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.support.v7.app.AlertDialog;
import com.nononsenseapps.filepicker.FilePickerActivity;
import org.schabi.newpipe.App;
import org.schabi.newpipe.MainActivity;
import org.schabi.newpipe.R;
import java.util.ArrayList;
import info.guardianproject.netcipher.proxy.OrbotHelper;
/**
* Created by david on 15/06/16.
*
* Copyright (C) Christian Schabesberger 2016 <chris.schabesberger@mailbox.org>
* SettingsFragment.java is part of NewPipe.
*
* NewPipe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NewPipe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
public class SettingsFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener
{
public static final int REQUEST_INSTALL_ORBOT = 0x1234;
SharedPreferences.OnSharedPreferenceChangeListener prefListener;
// get keys
String DEFAULT_RESOLUTION_PREFERENCE;
String DEFAULT_POPUP_RESOLUTION_PREFERENCE;
String PREFERRED_VIDEO_FORMAT_PREFERENCE;
String DEFAULT_AUDIO_FORMAT_PREFERENCE;
String SEARCH_LANGUAGE_PREFERENCE;
String DOWNLOAD_PATH_PREFERENCE;
String DOWNLOAD_PATH_AUDIO_PREFERENCE;
String USE_TOR_KEY;
String THEME;
private ListPreference defaultResolutionPreference;
private ListPreference defaultPopupResolutionPreference;
private ListPreference preferredVideoFormatPreference;
private ListPreference defaultAudioFormatPreference;
private ListPreference searchLanguagePreference;
private Preference downloadPathPreference;
private Preference downloadPathAudioPreference;
private Preference themePreference;
private SharedPreferences defaultPreferences;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
final Activity activity = getActivity();
defaultPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
// get keys
DEFAULT_RESOLUTION_PREFERENCE = getString(R.string.default_resolution_key);
DEFAULT_POPUP_RESOLUTION_PREFERENCE = getString(R.string.default_popup_resolution_key);
PREFERRED_VIDEO_FORMAT_PREFERENCE = getString(R.string.preferred_video_format_key);
DEFAULT_AUDIO_FORMAT_PREFERENCE = getString(R.string.default_audio_format_key);
SEARCH_LANGUAGE_PREFERENCE = getString(R.string.search_language_key);
DOWNLOAD_PATH_PREFERENCE = getString(R.string.download_path_key);
DOWNLOAD_PATH_AUDIO_PREFERENCE = getString(R.string.download_path_audio_key);
THEME = getString(R.string.theme_key);
USE_TOR_KEY = getString(R.string.use_tor_key);
// get pref objects
defaultResolutionPreference =
(ListPreference) findPreference(DEFAULT_RESOLUTION_PREFERENCE);
defaultPopupResolutionPreference =
(ListPreference) findPreference(DEFAULT_POPUP_RESOLUTION_PREFERENCE);
preferredVideoFormatPreference =
(ListPreference) findPreference(PREFERRED_VIDEO_FORMAT_PREFERENCE);
defaultAudioFormatPreference =
(ListPreference) findPreference(DEFAULT_AUDIO_FORMAT_PREFERENCE);
searchLanguagePreference =
(ListPreference) findPreference(SEARCH_LANGUAGE_PREFERENCE);
downloadPathPreference = findPreference(DOWNLOAD_PATH_PREFERENCE);
downloadPathAudioPreference = findPreference(DOWNLOAD_PATH_AUDIO_PREFERENCE);
themePreference = findPreference(THEME);
final String currentTheme = defaultPreferences.getString(THEME, "Light");
// TODO: Clean this, as the class is already implementing the class
// and those double equals...
prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Activity a = getActivity();
if(a == null)
{
return;
}
if (key == USE_TOR_KEY)
{
if (defaultPreferences.getBoolean(USE_TOR_KEY, false)) {
if (OrbotHelper.isOrbotInstalled(a)) {
App.configureTor(true);
OrbotHelper.requestStartTor(a);
} else {
Intent intent = OrbotHelper.getOrbotInstallIntent(a);
a.startActivityForResult(intent, REQUEST_INSTALL_ORBOT);
}
} else {
App.configureTor(false);
}
}
else if (key == DOWNLOAD_PATH_PREFERENCE)
{
String downloadPath = sharedPreferences
.getString(DOWNLOAD_PATH_PREFERENCE,
getString(R.string.download_path_summary));
downloadPathPreference
.setSummary(downloadPath);
}
else if (key == DOWNLOAD_PATH_AUDIO_PREFERENCE)
{
String downloadPath = sharedPreferences
.getString(DOWNLOAD_PATH_AUDIO_PREFERENCE,
getString(R.string.download_path_audio_summary));
downloadPathAudioPreference
.setSummary(downloadPath);
}
else if (key == THEME)
{
String selectedTheme = sharedPreferences.getString(THEME, "Light");
themePreference.setSummary(selectedTheme);
if(!selectedTheme.equals(currentTheme)) { // If it's not the current theme
new AlertDialog.Builder(activity)
.setTitle(R.string.restart_title)
.setMessage(R.string.msg_restart)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intentToMain = new Intent(activity, MainActivity.class);
intentToMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intentToMain);
activity.finish();
Runtime.getRuntime().exit(0);
}
})
.setNegativeButton(R.string.later, null)
.create().show();
}
}
updateSummary();
}
};
defaultPreferences.registerOnSharedPreferenceChangeListener(prefListener);
updateSummary();
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if(preference.getKey().equals(downloadPathPreference.getKey()) ||
preference.getKey().equals(downloadPathAudioPreference.getKey()))
{
Activity activity = getActivity();
Intent i = new Intent(activity, FilePickerActivity.class);
i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true);
i.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_DIR);
if(preference.getKey().equals(downloadPathPreference.getKey()))
{
activity.startActivityForResult(i, R.string.download_path_key);
}
else if (preference.getKey().equals(downloadPathAudioPreference.getKey()))
{
activity.startActivityForResult(i, R.string.download_path_audio_key);
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Activity a = getActivity();
if ((requestCode == R.string.download_path_audio_key
|| requestCode == R.string.download_path_key)
&& resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {
// For JellyBean and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ClipData clip = data.getClipData();
if (clip != null) {
for (int i = 0; i < clip.getItemCount(); i++) {
uri = clip.getItemAt(i).getUri();
}
}
// For Ice Cream Sandwich
} else {
ArrayList<String> paths = data.getStringArrayListExtra
(FilePickerActivity.EXTRA_PATHS);
if (paths != null) {
for (String path: paths) {
uri = Uri.parse(path);
}
}
}
} else {
uri = data.getData();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(a);
//requestCode is equal to R.string.download_path_key or
//R.string.download_path_audio_key
String key = getString(requestCode);
String path = data.getData().toString().substring(7);
prefs.edit()
.putString(key, path)
.apply();
}
else if(requestCode == REQUEST_INSTALL_ORBOT)
{
// try to start tor regardless of resultCode since clicking back after
// installing the app does not necessarily return RESULT_OK
App.configureTor(requestCode == REQUEST_INSTALL_ORBOT
&& OrbotHelper.requestStartTor(a));
}
updateSummary();
super.onActivityResult(requestCode, resultCode, data);
}
// This is used to show the status of some preference in the description
private void updateSummary() {
defaultResolutionPreference.setSummary(
defaultPreferences.getString(DEFAULT_RESOLUTION_PREFERENCE,
getString(R.string.default_resolution_value)));
defaultPopupResolutionPreference.setSummary(
defaultPreferences.getString(DEFAULT_POPUP_RESOLUTION_PREFERENCE,
getString(R.string.default_popup_resolution_value)));
preferredVideoFormatPreference.setSummary(
defaultPreferences.getString(PREFERRED_VIDEO_FORMAT_PREFERENCE,
getString(R.string.preferred_video_format_default)));
defaultAudioFormatPreference.setSummary(
defaultPreferences.getString(DEFAULT_AUDIO_FORMAT_PREFERENCE,
getString(R.string.default_audio_format_value)));
searchLanguagePreference.setSummary(
defaultPreferences.getString(SEARCH_LANGUAGE_PREFERENCE,
getString(R.string.default_language_value)));
downloadPathPreference.setSummary(
defaultPreferences.getString(DOWNLOAD_PATH_PREFERENCE,
getString(R.string.download_path_summary)));
downloadPathAudioPreference.setSummary(
defaultPreferences.getString(DOWNLOAD_PATH_AUDIO_PREFERENCE,
getString(R.string.download_path_audio_summary)));
themePreference.setSummary(
defaultPreferences.getString(THEME,
getString(R.string.light_theme_title)));
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}

View File

@@ -0,0 +1,8 @@
package org.schabi.newpipe.util;
public class Constants {
public static final String KEY_SERVICE_ID = "key_service_id";
public static final String KEY_URL = "key_url";
public static final String KEY_TITLE = "key_title";
public static final String KEY_LINK_TYPE = "key_link_type";
}

View File

@@ -0,0 +1,144 @@
package org.schabi.newpipe.util;
import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
import org.schabi.newpipe.MainActivity;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.extractor.StreamingService;
import org.schabi.newpipe.extractor.stream_info.AudioStream;
import org.schabi.newpipe.extractor.stream_info.StreamInfo;
import org.schabi.newpipe.fragments.OnItemSelectedListener;
import org.schabi.newpipe.fragments.detail.VideoDetailFragment;
import org.schabi.newpipe.player.BackgroundPlayer;
import org.schabi.newpipe.player.BasePlayer;
import org.schabi.newpipe.player.VideoPlayer;
@SuppressWarnings({"unused", "WeakerAccess"})
public class NavigationHelper {
public static Intent getOpenVideoPlayerIntent(Context context, Class targetClazz, StreamInfo info, int selectedStreamIndex) {
Intent mIntent = new Intent(context, targetClazz)
.putExtra(BasePlayer.VIDEO_TITLE, info.title)
.putExtra(BasePlayer.VIDEO_URL, info.webpage_url)
.putExtra(BasePlayer.VIDEO_THUMBNAIL_URL, info.thumbnail_url)
.putExtra(BasePlayer.CHANNEL_NAME, info.uploader)
.putExtra(VideoPlayer.INDEX_SEL_VIDEO_STREAM, selectedStreamIndex)
.putExtra(VideoPlayer.VIDEO_STREAMS_LIST, Utils.getSortedStreamVideosList(context, info.video_streams, info.video_only_streams, false))
.putExtra(VideoPlayer.VIDEO_ONLY_AUDIO_STREAM, Utils.getHighestQualityAudio(info.audio_streams));
if (info.start_position > 0) mIntent.putExtra(BasePlayer.START_POSITION, info.start_position * 1000);
return mIntent;
}
public static Intent getOpenVideoPlayerIntent(Context context, Class targetClazz, VideoPlayer instance) {
return new Intent(context, targetClazz)
.putExtra(BasePlayer.VIDEO_TITLE, instance.getVideoTitle())
.putExtra(BasePlayer.VIDEO_URL, instance.getVideoUrl())
.putExtra(BasePlayer.VIDEO_THUMBNAIL_URL, instance.getVideoThumbnailUrl())
.putExtra(BasePlayer.CHANNEL_NAME, instance.getChannelName())
.putExtra(VideoPlayer.INDEX_SEL_VIDEO_STREAM, instance.getSelectedStreamIndex())
.putExtra(VideoPlayer.VIDEO_STREAMS_LIST, instance.getVideoStreamsList())
.putExtra(VideoPlayer.VIDEO_ONLY_AUDIO_STREAM, instance.getAudioStream())
.putExtra(BasePlayer.START_POSITION, ((int) instance.getPlayer().getCurrentPosition()));
}
public static Intent getOpenBackgroundPlayerIntent(Context context, StreamInfo info) {
return getOpenBackgroundPlayerIntent(context, info, info.audio_streams.get(Utils.getPreferredAudioFormat(context, info.audio_streams)));
}
public static Intent getOpenBackgroundPlayerIntent(Context context, StreamInfo info, AudioStream audioStream) {
Intent mIntent = new Intent(context, BackgroundPlayer.class)
.putExtra(BasePlayer.VIDEO_TITLE, info.title)
.putExtra(BasePlayer.VIDEO_URL, info.webpage_url)
.putExtra(BasePlayer.VIDEO_THUMBNAIL_URL, info.thumbnail_url)
.putExtra(BasePlayer.CHANNEL_NAME, info.uploader)
.putExtra(BasePlayer.CHANNEL_NAME, info.uploader)
.putExtra(BackgroundPlayer.AUDIO_STREAM, audioStream);
if (info.start_position > 0) mIntent.putExtra(BasePlayer.START_POSITION, info.start_position * 1000);
return mIntent;
}
/*//////////////////////////////////////////////////////////////////////////
// Through Interface (faster)
//////////////////////////////////////////////////////////////////////////*/
public static void openChannel(OnItemSelectedListener listener, int serviceId, String url) {
openChannel(listener, serviceId, url, null);
}
public static void openChannel(OnItemSelectedListener listener, int serviceId, String url, String name) {
listener.onItemSelected(StreamingService.LinkType.CHANNEL, serviceId, url, name);
}
public static void openVideoDetail(OnItemSelectedListener listener, int serviceId, String url) {
openVideoDetail(listener, serviceId, url, null);
}
public static void openVideoDetail(OnItemSelectedListener listener, int serviceId, String url, String title) {
listener.onItemSelected(StreamingService.LinkType.STREAM, serviceId, url, title);
}
/*//////////////////////////////////////////////////////////////////////////
// Through Intents
//////////////////////////////////////////////////////////////////////////*/
public static void openByLink(Context context, String url) throws Exception {
context.startActivity(getIntentByLink(context, url));
}
public static void openChannel(Context context, int serviceId, String url) {
openChannel(context, serviceId, url, null);
}
public static void openChannel(Context context, int serviceId, String url, String name) {
Intent openIntent = getOpenIntent(context, url, serviceId, StreamingService.LinkType.CHANNEL);
if (name != null && !name.isEmpty()) openIntent.putExtra(Constants.KEY_TITLE, name);
context.startActivity(openIntent);
}
public static void openVideoDetail(Context context, int serviceId, String url) {
openVideoDetail(context, serviceId, url, null);
}
public static void openVideoDetail(Context context, int serviceId, String url, String title) {
Intent openIntent = getOpenIntent(context, url, serviceId, StreamingService.LinkType.STREAM);
if (title != null && !title.isEmpty()) openIntent.putExtra(Constants.KEY_TITLE, title);
context.startActivity(openIntent);
}
public static void openMainActivity(Context context) {
Intent mIntent = new Intent(context, MainActivity.class);
context.startActivity(mIntent);
}
private static Intent getOpenIntent(Context context, String url, int serviceId, StreamingService.LinkType type) {
Intent mIntent = new Intent(context, MainActivity.class);
mIntent.putExtra(Constants.KEY_SERVICE_ID, serviceId);
mIntent.putExtra(Constants.KEY_URL, url);
mIntent.putExtra(Constants.KEY_LINK_TYPE, type);
return mIntent;
}
private static Intent getIntentByLink(Context context, String url) throws Exception {
StreamingService service = NewPipe.getServiceByUrl(url);
if (service == null) throw new Exception("NewPipe.getServiceByUrl returned null for url > \"" + url + "\"");
int serviceId = service.getServiceId();
switch (service.getLinkTypeByUrl(url)) {
case STREAM:
Intent sIntent = getOpenIntent(context, url, serviceId, StreamingService.LinkType.STREAM);
sIntent.putExtra(VideoDetailFragment.AUTO_PLAY, PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(context.getString(R.string.autoplay_through_intent_key), false));
return sIntent;
case CHANNEL:
return getOpenIntent(context, url, serviceId, StreamingService.LinkType.CHANNEL);
case NONE:
throw new Exception("Url not known to service. service="
+ Integer.toString(serviceId) + " url=" + url);
}
return null;
}
}

View File

@@ -0,0 +1,95 @@
package org.schabi.newpipe.util;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
public class PermissionHelper {
public static final int PERMISSION_WRITE_STORAGE = 778;
public static final int PERMISSION_READ_STORAGE = 777;
public static final int PERMISSION_SYSTEM_ALERT_WINDOW = 779;
public static boolean checkStoragePermissions(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if(!checkReadStoragePermissions(activity)) return false;
}
return checkWriteStoragePermissions(activity);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkReadStoragePermissions(Activity activity) {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_READ_STORAGE);
return false;
}
return true;
}
public static boolean checkWriteStoragePermissions(Activity activity) {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
/*if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {*/
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_WRITE_STORAGE);
// PERMISSION_WRITE_STORAGE is an
// app-defined int constant. The callback method gets the
// result of the request.
/*}*/
return false;
}
return true;
}
/**
* In order to be able to draw over other apps, the permission android.permission.SYSTEM_ALERT_WINDOW have to be granted.
* <p>
* On < API 23 (MarshMallow) the permission was granted when the user installed the application (via AndroidManifest),
* on > 23, however, it have to start a activity asking the user if he agree.
* <p>
* This method just return if canDraw over other apps, if it doesn't, try to get the permission,
* it does not get the result of the startActivityForResult, if the user accept, the next time that he tries to open
* it will return true.
*
* @param activity context to startActivityForResult
* @return returns {@link Settings#canDrawOverlays(Context)}
**/
@RequiresApi(api = Build.VERSION_CODES.M)
public static boolean checkSystemAlertWindowPermission(Activity activity) {
if (!Settings.canDrawOverlays(activity)) {
Intent i = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + activity.getPackageName()));
activity.startActivityForResult(i, PERMISSION_SYSTEM_ALERT_WINDOW);
return false;
}else return true;
}
}

View File

@@ -0,0 +1,34 @@
package org.schabi.newpipe.util;
import android.content.Context;
import android.preference.PreferenceManager;
import org.schabi.newpipe.R;
public class ThemeHelper {
/**
* Apply the selected theme (on NewPipe settings) in the context
*
* @param context context that the theme will be applied
* @param useActionbarTheme whether to use an action bar theme or not
*/
public static void setTheme(Context context, boolean useActionbarTheme) {
String themeKey = context.getString(R.string.theme_key);
String darkTheme = context.getResources().getString(R.string.dark_theme_title);
String blackTheme = context.getResources().getString(R.string.black_theme_title);
String sp = PreferenceManager.getDefaultSharedPreferences(context)
.getString(themeKey, context.getResources().getString(R.string.light_theme_title));
if (useActionbarTheme) {
if (sp.equals(darkTheme)) context.setTheme(R.style.DarkTheme);
else if (sp.equals(blackTheme)) context.setTheme(R.style.BlackTheme);
else context.setTheme(R.style.AppTheme);
} else {
if (sp.equals(darkTheme)) context.setTheme(R.style.DarkTheme_NoActionBar);
else if (sp.equals(blackTheme)) context.setTheme(R.style.BlackTheme_NoActionBar);
else context.setTheme(R.style.AppTheme_NoActionBar);
}
}
}

View File

@@ -0,0 +1,273 @@
package org.schabi.newpipe.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.MediaFormat;
import org.schabi.newpipe.extractor.stream_info.AudioStream;
import org.schabi.newpipe.extractor.stream_info.VideoStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
@SuppressWarnings("WeakerAccess")
public class Utils {
private static final List<String> HIGH_RESOLUTION_LIST = Arrays.asList("1440p", "2160p", "1440p60", "2160p60");
/**
* Return the index of the default stream in the list, based on the parameters
* defaultResolution and preferredFormat
*
* @param videoStreams the list that will be extracted the index
*
* @return index of the preferred resolution&format
*/
public static int getDefaultResolution(String defaultResolution, String preferredFormat, List<VideoStream> videoStreams) {
if (defaultResolution.equals("Best resolution")) {
return 0;
}
// first try to find the one with the right resolution
int selectedFormat = 0;
for (int i = 0; i < videoStreams.size(); i++) {
VideoStream item = videoStreams.get(i);
if (defaultResolution.equals(item.resolution)) {
selectedFormat = i;
}
}
// than try to find the one with the right resolution and format
for (int i = 0; i < videoStreams.size(); i++) {
VideoStream item = videoStreams.get(i);
if (defaultResolution.equals(item.resolution)
&& preferredFormat.equals(MediaFormat.getNameById(item.format))) {
selectedFormat = i;
}
}
if (selectedFormat == 0 && !videoStreams.get(selectedFormat).resolution.contains(defaultResolution.replace("p60", "p"))) {
// Maybe there's no 60 fps variant available, so fallback to the normal version
String replace = defaultResolution.replace("p60", "p");
for (int i = 0; i < videoStreams.size(); i++) {
VideoStream item = videoStreams.get(i);
if (replace.equals(item.resolution)) selectedFormat = i;
}
// than try to find the one with the right resolution and format
for (int i = 0; i < videoStreams.size(); i++) {
VideoStream item = videoStreams.get(i);
if (replace.equals(item.resolution)
&& preferredFormat.equals(MediaFormat.getNameById(item.format))) {
selectedFormat = i;
}
}
}
// this is actually an error,
// but maybe there is really no stream fitting to the default value.
return selectedFormat;
}
/**
* @see #getDefaultResolution(String, String, List)
*/
public static int getDefaultResolution(Context context, List<VideoStream> videoStreams) {
SharedPreferences defaultPreferences = PreferenceManager.getDefaultSharedPreferences(context);
if (defaultPreferences == null) return 0;
String defaultResolution = defaultPreferences
.getString(context.getString(R.string.default_resolution_key), context.getString(R.string.default_resolution_value));
String preferredFormat = defaultPreferences
.getString(context.getString(R.string.preferred_video_format_key), context.getString(R.string.preferred_video_format_default));
return getDefaultResolution(defaultResolution, preferredFormat, videoStreams);
}
/**
* @see #getDefaultResolution(String, String, List)
*/
public static int getPopupDefaultResolution(Context context, List<VideoStream> videoStreams) {
SharedPreferences defaultPreferences = PreferenceManager.getDefaultSharedPreferences(context);
if (defaultPreferences == null) return 0;
String defaultResolution = defaultPreferences
.getString(context.getString(R.string.default_popup_resolution_key), context.getString(R.string.default_popup_resolution_value));
String preferredFormat = defaultPreferences
.getString(context.getString(R.string.preferred_video_format_key), context.getString(R.string.preferred_video_format_default));
return getDefaultResolution(defaultResolution, preferredFormat, videoStreams);
}
/**
* Return the index of the default stream in the list, based on the
* preferred audio format chosen in the settings
*
* @param context context to get the preferred audio format
* @param audioStreams the list that will be extracted the index
*
* @return index of the preferred format
*/
public static int getPreferredAudioFormat(Context context, List<AudioStream> audioStreams) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
if (sharedPreferences == null) return 0;
String preferredFormatString = sharedPreferences.getString(context.getString(R.string.default_audio_format_key), "webm");
int preferredFormat = MediaFormat.WEBMA.id;
switch (preferredFormatString) {
case "webm":
preferredFormat = MediaFormat.WEBMA.id;
break;
case "m4a":
preferredFormat = MediaFormat.M4A.id;
break;
default:
break;
}
int highestQualityIndex = 0;
// Try to find a audio stream with the preferred format
for (int i = 0; i < audioStreams.size(); i++) if (audioStreams.get(i).format == preferredFormat) highestQualityIndex = i;
// Try to find a audio stream with the highest bitrate and preferred format
for (int i = 0; i < audioStreams.size(); i++) {
AudioStream audioStream = audioStreams.get(i);
if (audioStream.avgBitrate > audioStreams.get(highestQualityIndex).avgBitrate
&& audioStream.format == preferredFormat) highestQualityIndex = i;
}
return highestQualityIndex;
}
/**
* Get the audio from the list with the highest bitrate
*
* @param audioStreams list the audio streams
* @return audio with highest average bitrate
*/
public static AudioStream getHighestQualityAudio(List<AudioStream> audioStreams) {
int highestQualityIndex = 0;
for (int i = 1; i < audioStreams.size(); i++) {
AudioStream audioStream = audioStreams.get(i);
if (audioStream.avgBitrate > audioStreams.get(highestQualityIndex).avgBitrate) highestQualityIndex = i;
}
return audioStreams.get(highestQualityIndex);
}
/**
* Join the two lists of video streams (video_only and normal videos), and sort them according with preferred format
* chosen by the user
*
* @param context context to search for the format to give preference
* @param videoStreams normal videos list
* @param videoOnlyStreams video only stream list
* @param ascendingOrder true -> smallest to greatest | false -> greatest to smallest
* @return the sorted list
*/
public static ArrayList<VideoStream> getSortedStreamVideosList(Context context, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder) {
boolean showHigherResolutions = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.show_higher_resolutions_key), false);
String preferredFormatString = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.preferred_video_format_key), context.getString(R.string.preferred_video_format_default));
MediaFormat preferredFormat = MediaFormat.WEBM;
switch (preferredFormatString) {
case "WebM":
preferredFormat = MediaFormat.WEBM;
break;
case "MPEG-4":
preferredFormat = MediaFormat.MPEG_4;
break;
case "3GPP":
preferredFormat = MediaFormat.v3GPP;
break;
default:
break;
}
return getSortedStreamVideosList(preferredFormat, showHigherResolutions, videoStreams, videoOnlyStreams, ascendingOrder);
}
/**
* Join the two lists of video streams (video_only and normal videos), and sort them according with preferred format
* chosen by the user
*
* @param preferredFormat format to give preference
* @param showHigherResolutions show >1080p resolutions
* @param videoStreams normal videos list
* @param videoOnlyStreams video only stream list
* @param ascendingOrder true -> smallest to greatest | false -> greatest to smallest @return the sorted list
* @return the sorted list
*/
public static ArrayList<VideoStream> getSortedStreamVideosList(MediaFormat preferredFormat, boolean showHigherResolutions, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder) {
ArrayList<VideoStream> retList = new ArrayList<>();
HashMap<String, VideoStream> hashMap = new HashMap<>();
if (videoOnlyStreams != null) {
for (VideoStream stream : videoOnlyStreams) {
if (!showHigherResolutions && HIGH_RESOLUTION_LIST.contains(stream.resolution)) continue;
retList.add(stream);
}
}
if (videoStreams != null) {
for (VideoStream stream : videoStreams) {
if (!showHigherResolutions && HIGH_RESOLUTION_LIST.contains(stream.resolution)) continue;
retList.add(stream);
}
}
// Add all to the hashmap
for (VideoStream videoStream : retList) hashMap.put(videoStream.resolution, videoStream);
// Override the values when the key == resolution, with the preferredFormat
for (VideoStream videoStream : retList) {
if (videoStream.format == preferredFormat.id) hashMap.put(videoStream.resolution, videoStream);
}
retList.clear();
retList.addAll(hashMap.values());
sortStreamList(retList, ascendingOrder);
return retList;
}
/**
* Sort the streams list depending on the parameter ascendingOrder;
* <p>
* It works like that:<br>
* - Take a string resolution, remove the letters, replace "0p60" (for 60fps videos) with "1"
* and sort by the greatest:<br>
* <blockquote><pre>
* 720p -> 720
* 720p60 -> 721
* 360p -> 360
* 1080p -> 1080
* 1080p60 -> 1081
* <p>
* ascendingOrder ? 360 < 720 < 721 < 1080 < 1081
* !ascendingOrder ? 1081 < 1080 < 721 < 720 < 360/pre></blockquote>
* <p>
* @param videoStreams list that the sorting will be applied
* @param ascendingOrder true -> smallest to greatest | false -> greatest to smallest
*/
public static void sortStreamList(List<VideoStream> videoStreams, final boolean ascendingOrder) {
Collections.sort(videoStreams, new Comparator<VideoStream>() {
@Override
public int compare(VideoStream o1, VideoStream o2) {
int res1 = Integer.parseInt(o1.resolution.replace("0p60", "1").replaceAll("[^\\d.]", ""));
int res2 = Integer.parseInt(o2.resolution.replace("0p60", "1").replaceAll("[^\\d.]", ""));
return ascendingOrder ? res1 - res2 : res2 - res1;
}
});
}
}

View File

@@ -0,0 +1,119 @@
package org.schabi.newpipe.workers;
import android.content.Context;
import org.schabi.newpipe.MainActivity;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.channel.ChannelExtractor;
import org.schabi.newpipe.extractor.channel.ChannelInfo;
import org.schabi.newpipe.extractor.exceptions.ExtractionException;
import org.schabi.newpipe.extractor.exceptions.ParsingException;
import org.schabi.newpipe.report.ErrorActivity;
import java.io.IOException;
/**
* Extract {@link ChannelInfo} with {@link ChannelExtractor} from the given url of the given service
*
* @author mauriciocolli
*/
@SuppressWarnings("WeakerAccess")
public class ChannelExtractorWorker extends ExtractorWorker {
//private static final String TAG = "ChannelExtractorWorker";
private int pageNumber;
private boolean onlyVideos;
private ChannelInfo channelInfo = null;
private OnChannelInfoReceive callback;
/**
* Interface which will be called for result and errors
*/
public interface OnChannelInfoReceive {
void onReceive(ChannelInfo info);
void onError(int messageId);
/**
* Called when an unrecoverable error has occurred.
* <p> This is a good place to finish the caller. </p>
*/
void onUnrecoverableError(Exception exception);
}
/**
* @param context context for error reporting purposes
* @param serviceId id of the request service
* @param channelUrl channelUrl of the service (e.g. https://www.youtube.com/channel/UC_aEa8K-EOJ3D6gOs7HcyNg)
* @param callback listener that will be called-back when events occur (check {@link ChannelExtractorWorker.OnChannelInfoReceive})
*/
public ChannelExtractorWorker(Context context, int serviceId, String channelUrl, int pageNumber, OnChannelInfoReceive callback) {
super(context, channelUrl, serviceId);
this.pageNumber = pageNumber;
this.callback = callback;
}
@Override
protected void onDestroy() {
super.onDestroy();
this.callback = null;
this.channelInfo = null;
}
@Override
protected void doWork(int serviceId, String url) throws Exception {
ChannelExtractor extractor = getService().getChannelExtractorInstance(url, pageNumber);
channelInfo = ChannelInfo.getInfo(extractor);
if (!channelInfo.errors.isEmpty()) handleErrorsDuringExtraction(channelInfo.errors, ErrorActivity.REQUESTED_CHANNEL);
if (callback != null && channelInfo != null && !isInterrupted()) getHandler().post(new Runnable() {
@Override
public void run() {
if (isInterrupted() || callback == null) return;
callback.onReceive(channelInfo);
onDestroy();
}
});
}
@Override
protected void handleException(final Exception exception, int serviceId, String url) {
if (callback == null || getHandler() == null || isInterrupted()) return;
if (exception instanceof IOException) {
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onError(R.string.network_error);
}
});
} else if (exception instanceof ParsingException || exception instanceof ExtractionException) {
ErrorActivity.reportError(getHandler(), getContext(), exception, MainActivity.class, null, ErrorActivity.ErrorInfo.make(ErrorActivity.REQUESTED_CHANNEL, getServiceName(), url, R.string.parsing_error));
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onUnrecoverableError(exception);
}
});
} else {
ErrorActivity.reportError(getHandler(), getContext(), exception, MainActivity.class, null, ErrorActivity.ErrorInfo.make(ErrorActivity.REQUESTED_CHANNEL, getServiceName(), url, R.string.general_error));
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onUnrecoverableError(exception);
}
});
}
}
public boolean isOnlyVideos() {
return onlyVideos;
}
public void setOnlyVideos(boolean onlyVideos) {
this.onlyVideos = onlyVideos;
}
}

View File

@@ -0,0 +1,161 @@
package org.schabi.newpipe.workers;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import org.schabi.newpipe.extractor.NewPipe;
import org.schabi.newpipe.extractor.StreamingService;
import org.schabi.newpipe.extractor.stream_info.StreamInfo;
import org.schabi.newpipe.report.ErrorActivity;
import java.io.InterruptedIOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Common properties of ExtractorWorkers
*
* @author mauriciocolli
*/
@SuppressWarnings("WeakerAccess")
public abstract class ExtractorWorker extends Thread {
private final AtomicBoolean isRunning = new AtomicBoolean(false);
private final String url;
private final int serviceId;
private Context context;
private Handler handler;
private StreamingService service;
public ExtractorWorker(Context context, String url, int serviceId) {
this.context = context;
this.url = url;
this.serviceId = serviceId;
this.handler = new Handler(context.getMainLooper());
if (url.length() >= 40) setName("Thread-" + url.substring(url.length() - 11, url.length()));
}
@Override
public void run() {
try {
isRunning.set(true);
service = NewPipe.getService(serviceId);
doWork(serviceId, url);
} catch (Exception e) {
// Handle the exception only if thread is not interrupted
if (!isInterrupted() && !(e instanceof InterruptedIOException) && !(e.getCause() instanceof InterruptedIOException)) {
handleException(e, serviceId, url);
}
} finally {
isRunning.set(false);
}
}
/**
* Here is the place that the heavy work is realized
*
* @param serviceId serviceId that was passed when created this object
* @param url url that was passed when created this object
*
* @throws Exception these exceptions are handled by the {@link #handleException(Exception, int, String)}
*/
protected abstract void doWork(int serviceId, String url) throws Exception;
/**
* Method that handle the exception thrown by the {@link #doWork(int, String)}.
*
* @param exception {@link Exception} that was thrown by {@link #doWork(int, String)}
*/
protected abstract void handleException(Exception exception, int serviceId, String url);
/**
* Handle the errors <b>during</b> extraction and shows a Report button to the user.<br/>
* Subclasses <b>maybe</b> call this method.
*
* @param errorsList list of exceptions that happened during extraction
* @param errorUserAction what action was the user performing during the error.
* (One of the {@link ErrorActivity}.REQUEST_* error (message) ids)
*/
protected void handleErrorsDuringExtraction(List<Throwable> errorsList, int errorUserAction){
String errorString = "<error id>";
switch (errorUserAction) {
case ErrorActivity.REQUESTED_STREAM:
errorString= ErrorActivity.REQUESTED_STREAM_STRING;
break;
case ErrorActivity.REQUESTED_CHANNEL:
errorString= ErrorActivity.REQUESTED_CHANNEL_STRING;
break;
}
Log.e(errorString, "OCCURRED ERRORS DURING EXTRACTION:");
for (Throwable e : errorsList) {
e.printStackTrace();
Log.e(errorString, "------");
}
if (getContext() instanceof Activity) {
View rootView = getContext() != null ? ((Activity) getContext()).findViewById(android.R.id.content) : null;
ErrorActivity.reportError(getHandler(), getContext(), errorsList, null, rootView, ErrorActivity.ErrorInfo.make(errorUserAction, getServiceName(), url, 0 /* no message for the user */));
}
}
/**
* Return true if the extraction is not completed yet
*
* @return the value of the AtomicBoolean {@link #isRunning}
*/
public boolean isRunning() {
return isRunning.get();
}
/**
* Cancel this ExtractorWorker, calling {@link #onDestroy()} and interrupting this thread.
* <p>
* <b>Note:</b> Any I/O that is active in the moment that this method is called will be canceled and a Exception will be thrown, because of the {@link #interrupt()}.<br>
* This is useful when you don't want the resulting {@link StreamInfo} anymore, but don't want to waste bandwidth, otherwise it'd run till it receives the StreamInfo.
*/
public void cancel() {
onDestroy();
this.interrupt();
}
/**
* Method that discards everything that doesn't need anymore.<br>
* Subclasses can override this method to destroy their garbage.
*/
protected void onDestroy() {
this.isRunning.set(false);
this.context = null;
this.handler = null;
this.service = null;
}
public Handler getHandler() {
return handler;
}
public String getUrl() {
return url;
}
public StreamingService getService() {
return service;
}
public int getServiceId() {
return serviceId;
}
public String getServiceName() {
return service == null ? "none" : service.getServiceInfo().name;
}
public Context getContext() {
return context;
}
}

View File

@@ -0,0 +1,165 @@
package org.schabi.newpipe.workers;
import android.content.Context;
import org.schabi.newpipe.MainActivity;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.exceptions.ParsingException;
import org.schabi.newpipe.extractor.exceptions.ReCaptchaException;
import org.schabi.newpipe.extractor.services.youtube.YoutubeStreamExtractor;
import org.schabi.newpipe.extractor.stream_info.StreamExtractor;
import org.schabi.newpipe.extractor.stream_info.StreamInfo;
import org.schabi.newpipe.report.ErrorActivity;
import java.io.IOException;
/**
* Extract {@link StreamInfo} with {@link StreamExtractor} from the given url of the given service
*
* @author mauriciocolli
*/
@SuppressWarnings("WeakerAccess")
public class StreamExtractorWorker extends ExtractorWorker {
//private static final String TAG = "StreamExtractorWorker";
private StreamInfo streamInfo = null;
private OnStreamInfoReceivedListener callback;
/**
* Interface which will be called for result and errors
*/
public interface OnStreamInfoReceivedListener {
void onReceive(StreamInfo info);
void onError(int messageId);
void onReCaptchaException();
void onBlockedByGemaError();
void onContentErrorWithMessage(int messageId);
void onContentError();
/**
* Called when an unrecoverable error has occurred.
* <p> This is a good place to finish the caller. </p>
*/
void onUnrecoverableError(Exception exception);
}
/**
* @param context context for error reporting purposes
* @param serviceId id of the request service
* @param videoUrl videoUrl of the service (e.g. https://www.youtube.com/watch?v=HyHNuVaZJ-k)
* @param callback listener that will be called-back when events occur (check {@link StreamExtractorWorker.OnStreamInfoReceivedListener})
*/
public StreamExtractorWorker(Context context, int serviceId, String videoUrl, OnStreamInfoReceivedListener callback) {
super(context, videoUrl, serviceId);
this.callback = callback;
}
@Override
protected void onDestroy() {
super.onDestroy();
this.callback = null;
this.streamInfo = null;
}
@Override
protected void doWork(int serviceId, String url) throws Exception {
StreamExtractor streamExtractor = getService().getExtractorInstance(url);
streamInfo = StreamInfo.getVideoInfo(streamExtractor);
if (streamInfo != null && !streamInfo.errors.isEmpty()) handleErrorsDuringExtraction(streamInfo.errors, ErrorActivity.REQUESTED_STREAM);
if (callback != null && getHandler() != null && streamInfo != null && !isInterrupted()) getHandler().post(new Runnable() {
@Override
public void run() {
if (isInterrupted() || callback == null) return;
callback.onReceive(streamInfo);
onDestroy();
}
});
}
@Override
protected void handleException(final Exception exception, int serviceId, final String url) {
if (callback == null || getHandler() == null || isInterrupted()) return;
if (exception instanceof ReCaptchaException) {
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onReCaptchaException();
}
});
} else if (exception instanceof IOException) {
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onError(R.string.network_error);
}
});
} else if (exception instanceof YoutubeStreamExtractor.GemaException) {
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onBlockedByGemaError();
}
});
} else if (exception instanceof YoutubeStreamExtractor.LiveStreamException) {
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onContentErrorWithMessage(R.string.live_streams_not_supported);
}
});
} else if (exception instanceof StreamExtractor.ContentNotAvailableException) {
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onContentError();
}
});
} else if (exception instanceof YoutubeStreamExtractor.DecryptException) {
// custom service related exceptions
ErrorActivity.reportError(getHandler(), getContext(), exception, MainActivity.class, null, ErrorActivity.ErrorInfo.make(ErrorActivity.REQUESTED_STREAM, getServiceName(), url, R.string.youtube_signature_decryption_error));
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onUnrecoverableError(exception);
}
});
} else if (exception instanceof StreamInfo.StreamExctractException) {
if (!streamInfo.errors.isEmpty()) {
// !!! if this case ever kicks in someone gets kicked out !!!
ErrorActivity.reportError(getHandler(), getContext(), exception, MainActivity.class, null, ErrorActivity.ErrorInfo.make(ErrorActivity.REQUESTED_STREAM, getServiceName(), url, R.string.could_not_get_stream));
} else {
ErrorActivity.reportError(getHandler(), getContext(), streamInfo.errors, MainActivity.class, null, ErrorActivity.ErrorInfo.make(ErrorActivity.REQUESTED_STREAM, getServiceName(), url, R.string.could_not_get_stream));
}
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onUnrecoverableError(exception);
}
});
} else if (exception instanceof ParsingException) {
ErrorActivity.reportError(getHandler(), getContext(), exception, MainActivity.class, null, ErrorActivity.ErrorInfo.make(ErrorActivity.REQUESTED_STREAM, getServiceName(), url, R.string.parsing_error));
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onUnrecoverableError(exception);
}
});
} else {
ErrorActivity.reportError(getHandler(), getContext(), exception, MainActivity.class, null, ErrorActivity.ErrorInfo.make(ErrorActivity.REQUESTED_STREAM, getServiceName(), url, R.string.general_error));
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onUnrecoverableError(exception);
}
});
}
}
}

View File

@@ -0,0 +1,36 @@
package us.shandian.giga.get;
import java.util.List;
/**
* Provides access to the storage of {@link DownloadMission}s
*/
public interface DownloadDataSource {
/**
* Load all missions
* @return a list of download missions
*/
List<DownloadMission> loadMissions();
/**
* Add a downlaod mission to the storage
* @param downloadMission the download mission to add
* @return the identifier of the mission
*/
void addMission(DownloadMission downloadMission);
/**
* Update a download mission which exists in the storage
* @param downloadMission the download mission to update
* @throws IllegalArgumentException if the mission was not added to storage
*/
void updateMission(DownloadMission downloadMission);
/**
* Delete a download mission
* @param downloadMission the mission to delete
*/
void deleteMission(DownloadMission downloadMission);
}

View File

@@ -0,0 +1,48 @@
package us.shandian.giga.get;
public interface DownloadManager
{
int BLOCK_SIZE = 512 * 1024;
/**
* Start a new download mission
* @param url the url to download
* @param location the location
* @param name the name of the file to create
* @param isAudio true if the download is an audio file
* @param threads the number of threads maximal used to download chunks of the file. @return the identifier of the mission.
*/
int startMission(String url, String location, String name, boolean isAudio, int threads);
/**
* Resume the execution of a download mission.
* @param id the identifier of the mission to resume.
*/
void resumeMission(int id);
/**
* Pause the execution of a download mission.
* @param id the identifier of the mission to pause.
*/
void pauseMission(int id);
/**
* Deletes the mission from the downloaded list but keeps the downloaded file.
* @param id The mission identifier
*/
void deleteMission(int id);
/**
* Get the download mission by its identifier
* @param id the identifier of the download mission
* @return the download mission or null if the mission doesn't exist
*/
DownloadMission getMission(int id);
/**
* Get the number of download missions.
* @return the number of download missions.
*/
int getCount();
}

View File

@@ -0,0 +1,367 @@
package us.shandian.giga.get;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import java.io.File;
import java.io.FilenameFilter;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import us.shandian.giga.util.Utility;
import static org.schabi.newpipe.BuildConfig.DEBUG;
public class DownloadManagerImpl implements DownloadManager
{
private static final String TAG = DownloadManagerImpl.class.getSimpleName();
private final DownloadDataSource mDownloadDataSource;
private final ArrayList<DownloadMission> mMissions = new ArrayList<DownloadMission>();
/**
* Create a new instance
* @param searchLocations the directories to search for unfinished downloads
* @param downloadDataSource the data source for finished downloads
*/
public DownloadManagerImpl(Collection<String> searchLocations, DownloadDataSource downloadDataSource) {
mDownloadDataSource = downloadDataSource;
loadMissions(searchLocations);
}
@Override
public int startMission(String url, String location, String name, boolean isAudio, int threads) {
DownloadMission existingMission = getMissionByLocation(location, name);
if(existingMission != null) {
// Already downloaded or downloading
if(existingMission.finished) {
// Overwrite mission
deleteMission(mMissions.indexOf(existingMission));
} else {
// Rename file (?)
try {
name = generateUniqueName(location, name);
}catch (Exception e) {
Log.e(TAG, "Unable to generate unique name", e);
name = System.currentTimeMillis() + name ;
Log.i(TAG, "Using " + name);
}
}
}
DownloadMission mission = new DownloadMission(name, url, location);
mission.timestamp = System.currentTimeMillis();
mission.threadCount = threads;
mission.addListener(new MissionListener(mission));
new Initializer(mission).start();
return insertMission(mission);
}
@Override
public void resumeMission(int i) {
DownloadMission d = getMission(i);
if (!d.running && d.errCode == -1) {
d.start();
}
}
@Override
public void pauseMission(int i) {
DownloadMission d = getMission(i);
if (d.running) {
d.pause();
}
}
@Override
public void deleteMission(int i) {
DownloadMission mission = getMission(i);
if(mission.finished) {
mDownloadDataSource.deleteMission(mission);
}
mission.delete();
mMissions.remove(i);
}
private void loadMissions(Iterable<String> searchLocations) {
mMissions.clear();
loadFinishedMissions();
for(String location: searchLocations) {
loadMissions(location);
}
}
/**
* Loads finished missions from the data source
*/
private void loadFinishedMissions() {
List<DownloadMission> finishedMissions = mDownloadDataSource.loadMissions();
if(finishedMissions == null) {
finishedMissions = new ArrayList<>();
}
// Ensure its sorted
Collections.sort(finishedMissions, new Comparator<DownloadMission>() {
@Override
public int compare(DownloadMission o1, DownloadMission o2) {
return (int) (o1.timestamp - o2.timestamp);
}
});
mMissions.ensureCapacity(mMissions.size() + finishedMissions.size());
for(DownloadMission mission: finishedMissions) {
File downloadedFile = mission.getDownloadedFile();
if(!downloadedFile.isFile()) {
if(DEBUG) {
Log.d(TAG, "downloaded file removed: " + downloadedFile.getAbsolutePath());
}
mDownloadDataSource.deleteMission(mission);
} else {
mission.length = downloadedFile.length();
mission.finished = true;
mission.running = false;
mMissions.add(mission);
}
}
}
private void loadMissions(String location) {
File f = new File(location);
if (f.exists() && f.isDirectory()) {
File[] subs = f.listFiles();
if(subs == null) {
Log.e(TAG, "listFiles() returned null");
return;
}
for (File sub : subs) {
if (sub.isFile() && sub.getName().endsWith(".giga")) {
String str = Utility.readFromFile(sub.getAbsolutePath());
if (str != null && !str.trim().equals("")) {
if (DEBUG) {
Log.d(TAG, "loading mission " + sub.getName());
Log.d(TAG, str);
}
DownloadMission mis = new Gson().fromJson(str, DownloadMission.class);
if (mis.finished) {
if(!sub.delete()) {
Log.w(TAG, "Unable to delete .giga file: " + sub.getPath());
}
continue;
}
mis.running = false;
mis.recovered = true;
insertMission(mis);
}
}
}
}
}
@Override
public DownloadMission getMission(int i) {
return mMissions.get(i);
}
@Override
public int getCount() {
return mMissions.size();
}
private int insertMission(DownloadMission mission) {
int i = -1;
DownloadMission m = null;
if (mMissions.size() > 0) {
do {
m = mMissions.get(++i);
} while (m.timestamp > mission.timestamp && i < mMissions.size() - 1);
//if (i > 0) i--;
} else {
i = 0;
}
mMissions.add(i, mission);
return i;
}
/**
* Get a mission by its location and name
* @param location the location
* @param name the name
* @return the mission or null if no such mission exists
*/
private @Nullable DownloadMission getMissionByLocation(String location, String name) {
for(DownloadMission mission: mMissions) {
if(location.equals(mission.location) && name.equals(mission.name)) {
return mission;
}
}
return null;
}
/**
* Splits the filename into name and extension
*
* Dots are ignored if they appear: not at all, at the beginning of the file,
* at the end of the file
*
* @param name the name to split
* @return a string array with a length of 2 containing the name and the extension
*/
private static String[] splitName(String name) {
int dotIndex = name.lastIndexOf('.');
if(dotIndex <= 0 || (dotIndex == name.length() - 1)) {
return new String[]{name, ""};
} else {
return new String[]{name.substring(0, dotIndex), name.substring(dotIndex + 1)};
}
}
/**
* Generates a unique file name.
*
* e.g. "myname (1).txt" if the name "myname.txt" exists.
* @param location the location (to check for existing files)
* @param name the name of the file
* @return the unique file name
* @throws IllegalArgumentException if the location is not a directory
* @throws SecurityException if the location is not readable
*/
private static String generateUniqueName(String location, String name) {
if(location == null) throw new NullPointerException("location is null");
if(name == null) throw new NullPointerException("name is null");
File destination = new File(location);
if(!destination.isDirectory()) {
throw new IllegalArgumentException("location is not a directory: " + location);
}
final String[] nameParts = splitName(name);
String[] existingName = destination.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(nameParts[0]);
}
});
Arrays.sort(existingName);
String newName;
int downloadIndex = 0;
do {
newName = nameParts[0] + " (" + downloadIndex + ")." + nameParts[1];
++downloadIndex;
if(downloadIndex == 1000) { // Probably an error on our side
throw new RuntimeException("Too many existing files");
}
} while (Arrays.binarySearch(existingName, newName) >= 0);
return newName;
}
private class Initializer extends Thread {
private DownloadMission mission;
public Initializer(DownloadMission mission) {
this.mission = mission;
}
@Override
public void run() {
try {
URL url = new URL(mission.url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
mission.length = conn.getContentLength();
if (mission.length <= 0) {
mission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;
//mission.notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);
return;
}
// Open again
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Range", "bytes=" + (mission.length - 10) + "-" + mission.length);
if (conn.getResponseCode() != 206) {
// Fallback to single thread if no partial content support
mission.fallback = true;
if (DEBUG) {
Log.d(TAG, "falling back");
}
}
if (DEBUG) {
Log.d(TAG, "response = " + conn.getResponseCode());
}
mission.blocks = mission.length / BLOCK_SIZE;
if (mission.threadCount > mission.blocks) {
mission.threadCount = (int) mission.blocks;
}
if (mission.threadCount <= 0) {
mission.threadCount = 1;
}
if (mission.blocks * BLOCK_SIZE < mission.length) {
mission.blocks++;
}
new File(mission.location).mkdirs();
new File(mission.location + "/" + mission.name).createNewFile();
RandomAccessFile af = new RandomAccessFile(mission.location + "/" + mission.name, "rw");
af.setLength(mission.length);
af.close();
mission.start();
} catch (Exception e) {
// TODO Notify
throw new RuntimeException(e);
}
}
}
/**
* Waits for mission to finish to add it to the {@link #mDownloadDataSource}
*/
private class MissionListener implements DownloadMission.MissionListener {
private final DownloadMission mMission;
private MissionListener(DownloadMission mission) {
if(mission == null) throw new NullPointerException("mission is null");
// Could the mission be passed in onFinish()?
mMission = mission;
}
@Override
public void onProgressUpdate(DownloadMission downloadMission, long done, long total) {
}
@Override
public void onFinish(DownloadMission downloadMission) {
mDownloadDataSource.addMission(mMission);
}
@Override
public void onError(DownloadMission downloadMission, int errCode) {
}
}
}

View File

@@ -0,0 +1,328 @@
package us.shandian.giga.get;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.google.gson.Gson;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import us.shandian.giga.util.Utility;
import static org.schabi.newpipe.BuildConfig.DEBUG;
public class DownloadMission
{
private static final String TAG = DownloadMission.class.getSimpleName();
public interface MissionListener {
HashMap<MissionListener, Handler> handlerStore = new HashMap<>();
void onProgressUpdate(DownloadMission downloadMission, long done, long total);
void onFinish(DownloadMission downloadMission);
void onError(DownloadMission downloadMission, int errCode);
}
public static final int ERROR_SERVER_UNSUPPORTED = 206;
public static final int ERROR_UNKNOWN = 233;
/**
* The filename
*/
public String name;
/**
* The url of the file to download
*/
public String url;
/**
* The directory to store the download
*/
public String location;
/**
* Number of blocks the size of {@link DownloadManager#BLOCK_SIZE}
*/
public long blocks;
/**
* Number of bytes
*/
public long length;
/**
* Number of bytes downloaded
*/
public long done;
public int threadCount = 3;
public int finishCount;
private List<Long> threadPositions = new ArrayList<Long>();
public final Map<Long, Boolean> blockState = new HashMap<Long, Boolean>();
public boolean running;
public boolean finished;
public boolean fallback;
public int errCode = -1;
public long timestamp;
public transient boolean recovered;
private transient ArrayList<WeakReference<MissionListener>> mListeners = new ArrayList<WeakReference<MissionListener>>();
private transient boolean mWritingToFile;
private static final int NO_IDENTIFIER = -1;
private long db_identifier = NO_IDENTIFIER;
public DownloadMission() {
}
public DownloadMission(String name, String url, String location) {
if(name == null) throw new NullPointerException("name is null");
if(name.isEmpty()) throw new IllegalArgumentException("name is empty");
if(url == null) throw new NullPointerException("url is null");
if(url.isEmpty()) throw new IllegalArgumentException("url is empty");
if(location == null) throw new NullPointerException("location is null");
if(location.isEmpty()) throw new IllegalArgumentException("location is empty");
this.url = url;
this.name = name;
this.location = location;
}
private void checkBlock(long block) {
if(block < 0 || block >= blocks) {
throw new IllegalArgumentException("illegal block identifier");
}
}
/**
* Check if a block is reserved
* @param block the block identifier
* @return true if the block is reserved and false if otherwise
*/
public boolean isBlockPreserved(long block) {
checkBlock(block);
return blockState.containsKey(block) ? blockState.get(block) : false;
}
public void preserveBlock(long block) {
checkBlock(block);
synchronized (blockState) {
blockState.put(block, true);
}
}
/**
* Set the download position of the file
* @param threadId the identifier of the thread
* @param position the download position of the thread
*/
public void setPosition(int threadId, long position) {
threadPositions.set(threadId, position);
}
/**
* Get the position of a thread
* @param threadId the identifier of the thread
* @return the position for the thread
*/
public long getPosition(int threadId) {
return threadPositions.get(threadId);
}
public synchronized void notifyProgress(long deltaLen) {
if (!running) return;
if (recovered) {
recovered = false;
}
done += deltaLen;
if (done > length) {
done = length;
}
if (done != length) {
writeThisToFile();
}
for (WeakReference<MissionListener> ref: mListeners) {
final MissionListener listener = ref.get();
if (listener != null) {
MissionListener.handlerStore.get(listener).post(new Runnable() {
@Override
public void run() {
listener.onProgressUpdate(DownloadMission.this, done, length);
}
});
}
}
}
/**
* Called by a download thread when it finished.
*/
public synchronized void notifyFinished() {
if (errCode > 0) return;
finishCount++;
if (finishCount == threadCount) {
onFinish();
}
}
/**
* Called when all parts are downloaded
*/
private void onFinish() {
if (errCode > 0) return;
if (DEBUG) {
Log.d(TAG, "onFinish");
}
running = false;
finished = true;
deleteThisFromFile();
for (WeakReference<MissionListener> ref : mListeners) {
final MissionListener listener = ref.get();
if (listener != null) {
MissionListener.handlerStore.get(listener).post(new Runnable() {
@Override
public void run() {
listener.onFinish(DownloadMission.this);
}
});
}
}
}
public synchronized void notifyError(int err) {
errCode = err;
writeThisToFile();
for (WeakReference<MissionListener> ref : mListeners) {
final MissionListener listener = ref.get();
MissionListener.handlerStore.get(listener).post(new Runnable() {
@Override
public void run() {
listener.onError(DownloadMission.this, errCode);
}
});
}
}
public synchronized void addListener(MissionListener listener) {
Handler handler = new Handler(Looper.getMainLooper());
MissionListener.handlerStore.put(listener, handler);
mListeners.add(new WeakReference<MissionListener>(listener));
}
public synchronized void removeListener(MissionListener listener) {
for (Iterator<WeakReference<MissionListener>> iterator = mListeners.iterator();
iterator.hasNext(); ) {
WeakReference<MissionListener> weakRef = iterator.next();
if (listener!=null && listener == weakRef.get())
{
iterator.remove();
}
}
}
/**
* Start downloading with multiple threads.
*/
public void start() {
if (!running && !finished) {
running = true;
if (!fallback) {
for (int i = 0; i < threadCount; i++) {
if (threadPositions.size() <= i && !recovered) {
threadPositions.add((long) i);
}
new Thread(new DownloadRunnable(this, i)).start();
}
} else {
// In fallback mode, resuming is not supported.
threadCount = 1;
done = 0;
blocks = 0;
new Thread(new DownloadRunnableFallback(this)).start();
}
}
}
public void pause() {
if (running) {
running = false;
recovered = true;
// TODO: Notify & Write state to info file
// if (err)
}
}
/**
* Removes the file and the meta file
*/
public void delete() {
deleteThisFromFile();
new File(location, name).delete();
}
/**
* Write this {@link DownloadMission} to the meta file asynchronously
* if no thread is already running.
*/
public void writeThisToFile() {
if (!mWritingToFile) {
mWritingToFile = true;
new Thread() {
@Override
public void run() {
doWriteThisToFile();
mWritingToFile = false;
}
}.start();
}
}
/**
* Write this {@link DownloadMission} to the meta file.
*/
private void doWriteThisToFile() {
synchronized (blockState) {
Utility.writeToFile(getMetaFilename(), new Gson().toJson(this));
}
}
private void deleteThisFromFile() {
new File(getMetaFilename()).delete();
}
/**
* Get the path of the meta file
* @return the path to the meta file
*/
private String getMetaFilename() {
return location + "/" + name + ".giga";
}
public File getDownloadedFile() {
return new File(location, name);
}
}

View File

@@ -0,0 +1,178 @@
package us.shandian.giga.get;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import static org.schabi.newpipe.BuildConfig.DEBUG;
/**
* Runnable to download blocks of a file until the file is completely downloaded,
* an error occurs or the process is stopped.
*/
public class DownloadRunnable implements Runnable
{
private static final String TAG = DownloadRunnable.class.getSimpleName();
private final DownloadMission mMission;
private final int mId;
public DownloadRunnable(DownloadMission mission, int id) {
if(mission == null) throw new NullPointerException("mission is null");
mMission = mission;
mId = id;
}
@Override
public void run() {
boolean retry = mMission.recovered;
long position = mMission.getPosition(mId);
if (DEBUG) {
Log.d(TAG, mId + ":default pos " + position);
Log.d(TAG, mId + ":recovered: " + mMission.recovered);
}
while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {
if (Thread.currentThread().isInterrupted()) {
mMission.pause();
return;
}
if (DEBUG && retry) {
Log.d(TAG, mId + ":retry is true. Resuming at " + position);
}
// Wait for an unblocked position
while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {
if (DEBUG) {
Log.d(TAG, mId + ":position " + position + " preserved, passing");
}
position++;
}
retry = false;
if (position >= mMission.blocks) {
break;
}
if (DEBUG) {
Log.d(TAG, mId + ":preserving position " + position);
}
mMission.preserveBlock(position);
mMission.setPosition(mId, position);
long start = position * DownloadManager.BLOCK_SIZE;
long end = start + DownloadManager.BLOCK_SIZE - 1;
if (end >= mMission.length) {
end = mMission.length - 1;
}
HttpURLConnection conn = null;
int total = 0;
try {
URL url = new URL(mMission.url);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
if (DEBUG) {
Log.d(TAG, mId + ":" + conn.getRequestProperty("Range"));
Log.d(TAG, mId + ":Content-Length=" + conn.getContentLength() + " Code:" + conn.getResponseCode());
}
// A server may be ignoring the range request
if (conn.getResponseCode() != 206) {
mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;
notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);
if (DEBUG) {
Log.e(TAG, mId + ":Unsupported " + conn.getResponseCode());
}
break;
}
RandomAccessFile f = new RandomAccessFile(mMission.location + "/" + mMission.name, "rw");
f.seek(start);
BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());
byte[] buf = new byte[512];
while (start < end && mMission.running) {
int len = ipt.read(buf, 0, 512);
if (len == -1) {
break;
} else {
start += len;
total += len;
f.write(buf, 0, len);
notifyProgress(len);
}
}
if (DEBUG && mMission.running) {
Log.d(TAG, mId + ":position " + position + " finished, total length " + total);
}
f.close();
ipt.close();
// TODO We should save progress for each thread
} catch (Exception e) {
// TODO Retry count limit & notify error
retry = true;
notifyProgress(-total);
if (DEBUG) {
Log.d(TAG, mId + ":position " + position + " retrying", e);
}
}
}
if (DEBUG) {
Log.d(TAG, "thread " + mId + " exited main loop");
}
if (mMission.errCode == -1 && mMission.running) {
if (DEBUG) {
Log.d(TAG, "no error has happened, notifying");
}
notifyFinished();
}
if (DEBUG && !mMission.running) {
Log.d(TAG, "The mission has been paused. Passing.");
}
}
private void notifyProgress(final long len) {
synchronized (mMission) {
mMission.notifyProgress(len);
}
}
private void notifyError(final int err) {
synchronized (mMission) {
mMission.notifyError(err);
mMission.pause();
}
}
private void notifyFinished() {
synchronized (mMission) {
mMission.notifyFinished();
}
}
}

View File

@@ -0,0 +1,75 @@
package us.shandian.giga.get;
import java.io.BufferedInputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
// Single-threaded fallback mode
public class DownloadRunnableFallback implements Runnable
{
private final DownloadMission mMission;
//private int mId;
public DownloadRunnableFallback(DownloadMission mission) {
if(mission == null) throw new NullPointerException("mission is null");
//mId = id;
mMission = mission;
}
@Override
public void run() {
try {
URL url = new URL(mMission.url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200 && conn.getResponseCode() != 206) {
notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);
} else {
RandomAccessFile f = new RandomAccessFile(mMission.location + "/" + mMission.name, "rw");
f.seek(0);
BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());
byte[] buf = new byte[512];
int len = 0;
while ((len = ipt.read(buf, 0, 512)) != -1 && mMission.running) {
f.write(buf, 0, len);
notifyProgress(len);
if (Thread.interrupted()) {
break;
}
}
f.close();
ipt.close();
}
} catch (Exception e) {
notifyError(DownloadMission.ERROR_UNKNOWN);
}
if (mMission.errCode == -1 && mMission.running) {
notifyFinished();
}
}
private void notifyProgress(final long len) {
synchronized (mMission) {
mMission.notifyProgress(len);
}
}
private void notifyError(final int err) {
synchronized (mMission) {
mMission.notifyError(err);
mMission.pause();
}
}
private void notifyFinished() {
synchronized (mMission) {
mMission.notifyFinished();
}
}
}

View File

@@ -0,0 +1,102 @@
package us.shandian.giga.get.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import us.shandian.giga.get.DownloadMission;
/**
* SqliteHelper to store {@link us.shandian.giga.get.DownloadMission}
*/
public class DownloadMissionSQLiteHelper extends SQLiteOpenHelper {
private final String TAG = "DownloadMissionHelper";
// TODO: use NewPipeSQLiteHelper ('s constants) when playlist branch is merged (?)
private static final String DATABASE_NAME = "downloads.db";
private static final int DATABASE_VERSION = 2;
/**
* The table name of download missions
*/
static final String MISSIONS_TABLE_NAME = "download_missions";
/**
* The key to the directory location of the mission
*/
static final String KEY_LOCATION = "location";
/**
* The key to the url of a mission
*/
static final String KEY_URL = "url";
/**
* The key to the name of a mission
*/
static final String KEY_NAME = "name";
/**
* The key to the done.
*/
static final String KEY_DONE = "bytes_downloaded";
static final String KEY_TIMESTAMP = "timestamp";
/**
* The statement to create the table
*/
private static final String MISSIONS_CREATE_TABLE =
"CREATE TABLE " + MISSIONS_TABLE_NAME + " (" +
KEY_LOCATION + " TEXT NOT NULL, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_URL + " TEXT NOT NULL, " +
KEY_DONE + " INTEGER NOT NULL, " +
KEY_TIMESTAMP + " INTEGER NOT NULL, " +
" UNIQUE(" + KEY_LOCATION + ", " + KEY_NAME + "));";
DownloadMissionSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Returns all values of the download mission as ContentValues.
* @param downloadMission the download mission
* @return the content values
*/
public static ContentValues getValuesOfMission(DownloadMission downloadMission) {
ContentValues values = new ContentValues();
values.put(KEY_URL, downloadMission.url);
values.put(KEY_LOCATION, downloadMission.location);
values.put(KEY_NAME, downloadMission.name);
values.put(KEY_DONE, downloadMission.done);
values.put(KEY_TIMESTAMP, downloadMission.timestamp);
return values;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(MISSIONS_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Currently nothing to do
}
public static DownloadMission getMissionFromCursor(Cursor cursor) {
if(cursor == null) throw new NullPointerException("cursor is null");
int pos;
String name = cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAME));
String location = cursor.getString(cursor.getColumnIndexOrThrow(KEY_LOCATION));
String url = cursor.getString(cursor.getColumnIndexOrThrow(KEY_URL));
DownloadMission mission = new DownloadMission(name, url, location);
mission.done = cursor.getLong(cursor.getColumnIndexOrThrow(KEY_DONE));
mission.timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(KEY_TIMESTAMP));
mission.finished = true;
return mission;
}
}

View File

@@ -0,0 +1,79 @@
package us.shandian.giga.get.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import us.shandian.giga.get.DownloadDataSource;
import us.shandian.giga.get.DownloadMission;
import static us.shandian.giga.get.sqlite.DownloadMissionSQLiteHelper.KEY_LOCATION;
import static us.shandian.giga.get.sqlite.DownloadMissionSQLiteHelper.KEY_NAME;
import static us.shandian.giga.get.sqlite.DownloadMissionSQLiteHelper.MISSIONS_TABLE_NAME;
/**
* Non-thread-safe implementation of {@link DownloadDataSource}
*/
public class SQLiteDownloadDataSource implements DownloadDataSource {
private static final String TAG = "DownloadDataSourceImpl";
private final DownloadMissionSQLiteHelper downloadMissionSQLiteHelper;
public SQLiteDownloadDataSource(Context context) {
downloadMissionSQLiteHelper = new DownloadMissionSQLiteHelper(context);
}
@Override
public List<DownloadMission> loadMissions() {
ArrayList<DownloadMission> result;
SQLiteDatabase database = downloadMissionSQLiteHelper.getReadableDatabase();
Cursor cursor = database.query(MISSIONS_TABLE_NAME, null, null,
null, null, null, DownloadMissionSQLiteHelper.KEY_TIMESTAMP);
int count = cursor.getCount();
if(count == 0) return new ArrayList<>();
result = new ArrayList<>(count);
while (cursor.moveToNext()) {
result.add(DownloadMissionSQLiteHelper.getMissionFromCursor(cursor));
}
return result;
}
@Override
public void addMission(DownloadMission downloadMission) {
if(downloadMission == null) throw new NullPointerException("downloadMission is null");
SQLiteDatabase database = downloadMissionSQLiteHelper.getWritableDatabase();
ContentValues values = DownloadMissionSQLiteHelper.getValuesOfMission(downloadMission);
database.insert(MISSIONS_TABLE_NAME, null, values);
}
@Override
public void updateMission(DownloadMission downloadMission) {
if(downloadMission == null) throw new NullPointerException("downloadMission is null");
SQLiteDatabase database = downloadMissionSQLiteHelper.getWritableDatabase();
ContentValues values = DownloadMissionSQLiteHelper.getValuesOfMission(downloadMission);
String whereClause = KEY_LOCATION+ " = ? AND " +
KEY_NAME + " = ?";
int rowsAffected = database.update(MISSIONS_TABLE_NAME, values,
whereClause, new String[]{downloadMission.location, downloadMission.name});
if(rowsAffected != 1) {
Log.e(TAG, "Expected 1 row to be affected by update but got " + rowsAffected);
}
}
@Override
public void deleteMission(DownloadMission downloadMission) {
if(downloadMission == null) throw new NullPointerException("downloadMission is null");
SQLiteDatabase database = downloadMissionSQLiteHelper.getWritableDatabase();
database.delete(MISSIONS_TABLE_NAME,
KEY_LOCATION + " = ? AND " +
KEY_NAME + " = ?",
new String[]{downloadMission.location, downloadMission.name});
}
}

View File

@@ -0,0 +1,270 @@
package us.shandian.giga.service;
import android.Manifest;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat.Builder;
import android.support.v4.content.PermissionChecker;
import android.util.Log;
import android.widget.Toast;
import org.schabi.newpipe.R;
import org.schabi.newpipe.download.DownloadActivity;
import org.schabi.newpipe.settings.NewPipeSettings;
import java.util.ArrayList;
import us.shandian.giga.get.DownloadDataSource;
import us.shandian.giga.get.DownloadManager;
import us.shandian.giga.get.DownloadManagerImpl;
import us.shandian.giga.get.DownloadMission;
import us.shandian.giga.get.sqlite.SQLiteDownloadDataSource;
import static org.schabi.newpipe.BuildConfig.DEBUG;
public class DownloadManagerService extends Service
{
private static final String TAG = DownloadManagerService.class.getSimpleName();
/**
* Message code of update messages stored as {@link Message#what}.
*/
private static final int UPDATE_MESSAGE = 0;
private static final int NOTIFICATION_ID = 1000;
private static final String EXTRA_NAME = "DownloadManagerService.extra.name";
private static final String EXTRA_LOCATION = "DownloadManagerService.extra.location";
private static final String EXTRA_IS_AUDIO = "DownloadManagerService.extra.is_audio";
private static final String EXTRA_THREADS = "DownloadManagerService.extra.threads";
private DMBinder mBinder;
private DownloadManager mManager;
private Notification mNotification;
private Handler mHandler;
private long mLastTimeStamp = System.currentTimeMillis();
private DownloadDataSource mDataSource;
private MissionListener missionListener = new MissionListener();
private void notifyMediaScanner(DownloadMission mission) {
Uri uri = Uri.parse("file://" + mission.location + "/" + mission.name);
// notify media scanner on downloaded media file ...
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
}
@Override
public void onCreate() {
super.onCreate();
if (DEBUG) {
Log.d(TAG, "onCreate");
}
mBinder = new DMBinder();
if(mDataSource == null) {
mDataSource = new SQLiteDownloadDataSource(this);
}
if (mManager == null) {
ArrayList<String> paths = new ArrayList<>(2);
paths.add(NewPipeSettings.getVideoDownloadPath(this));
paths.add(NewPipeSettings.getAudioDownloadPath(this));
mManager = new DownloadManagerImpl(paths, mDataSource);
if (DEBUG) {
Log.d(TAG, "mManager == null");
Log.d(TAG, "Download directory: " + paths);
}
}
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.setClass(this, DownloadActivity.class);
Drawable icon = this.getResources().getDrawable(R.mipmap.ic_launcher);
Builder builder = new Builder(this)
.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))
.setSmallIcon(android.R.drawable.stat_sys_download)
.setLargeIcon(((BitmapDrawable) icon).getBitmap())
.setContentTitle(getString(R.string.msg_running))
.setContentText(getString(R.string.msg_running_detail));
PendingIntent pendingIntent =
PendingIntent.getActivity(
this,
0,
new Intent(this, DownloadActivity.class)
.setAction(DownloadActivity.INTENT_LIST),
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(pendingIntent);
mNotification = builder.build();
HandlerThread thread = new HandlerThread("ServiceMessenger");
thread.start();
mHandler = new Handler(thread.getLooper()) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_MESSAGE: {
int runningCount = 0;
for (int i = 0; i < mManager.getCount(); i++) {
if (mManager.getMission(i).running) {
runningCount++;
}
}
updateState(runningCount);
break;
}
}
}
};
}
private void startMissionAsync(final String url, final String location, final String name,
final boolean isAudio, final int threads) {
mHandler.post(new Runnable() {
@Override
public void run() {
int missionId = mManager.startMission(url, location, name, isAudio, threads);
mBinder.onMissionAdded(mManager.getMission(missionId));
}
});
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (DEBUG) {
Log.d(TAG, "Starting");
}
Log.i(TAG, "Got intent: " + intent);
String action = intent.getAction();
if(action != null && action.equals(Intent.ACTION_RUN)) {
String name = intent.getStringExtra(EXTRA_NAME);
String location = intent.getStringExtra(EXTRA_LOCATION);
int threads = intent.getIntExtra(EXTRA_THREADS, 1);
boolean isAudio = intent.getBooleanExtra(EXTRA_IS_AUDIO, false);
String url = intent.getDataString();
startMissionAsync(url, location, name, isAudio, threads);
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (DEBUG) {
Log.d(TAG, "Destroying");
}
for (int i = 0; i < mManager.getCount(); i++) {
mManager.pauseMission(i);
}
stopForeground(true);
}
@Override
public IBinder onBind(Intent intent) {
int permissionCheck;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
permissionCheck = PermissionChecker.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if(permissionCheck == PermissionChecker.PERMISSION_DENIED) {
Toast.makeText(this, "Permission denied (read)", Toast.LENGTH_SHORT).show();
}
}
permissionCheck = PermissionChecker.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(permissionCheck == PermissionChecker.PERMISSION_DENIED) {
Toast.makeText(this, "Permission denied (write)", Toast.LENGTH_SHORT).show();
}
return mBinder;
}
private void postUpdateMessage() {
mHandler.sendEmptyMessage(UPDATE_MESSAGE);
}
private void updateState(int runningCount) {
if (runningCount == 0) {
stopForeground(true);
} else {
startForeground(NOTIFICATION_ID, mNotification);
}
}
public static void startMission(Context context, String url, String location, String name, boolean isAudio, int threads) {
Intent intent = new Intent(context, DownloadManagerService.class);
intent.setAction(Intent.ACTION_RUN);
intent.setData(Uri.parse(url));
intent.putExtra(EXTRA_NAME, name);
intent.putExtra(EXTRA_LOCATION, location);
intent.putExtra(EXTRA_IS_AUDIO, isAudio);
intent.putExtra(EXTRA_THREADS, threads);
context.startService(intent);
}
class MissionListener implements DownloadMission.MissionListener {
@Override
public void onProgressUpdate(DownloadMission downloadMission, long done, long total) {
long now = System.currentTimeMillis();
long delta = now - mLastTimeStamp;
if (delta > 2000) {
postUpdateMessage();
mLastTimeStamp = now;
}
}
@Override
public void onFinish(DownloadMission downloadMission) {
postUpdateMessage();
notifyMediaScanner(downloadMission);
}
@Override
public void onError(DownloadMission downloadMission, int errCode) {
postUpdateMessage();
}
}
// Wrapper of DownloadManager
public class DMBinder extends Binder {
public DownloadManager getDownloadManager() {
return mManager;
}
public void onMissionAdded(DownloadMission mission) {
mission.addListener(missionListener);
postUpdateMessage();
}
public void onMissionRemoved(DownloadMission mission) {
mission.removeListener(missionListener);
postUpdateMessage();
}
}
}

View File

@@ -0,0 +1,375 @@
package us.shandian.giga.ui.adapter;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.support.v7.widget.RecyclerView;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.schabi.newpipe.R;
import us.shandian.giga.get.DownloadManager;
import us.shandian.giga.get.DownloadMission;
import us.shandian.giga.service.DownloadManagerService;
import us.shandian.giga.ui.common.ProgressDrawable;
import us.shandian.giga.util.Utility;
import static android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;
public class MissionAdapter extends RecyclerView.Adapter<MissionAdapter.ViewHolder>
{
private static final Map<Integer, String> ALGORITHMS = new HashMap<>();
private static final String TAG = "MissionAdapter";
static {
ALGORITHMS.put(R.id.md5, "MD5");
ALGORITHMS.put(R.id.sha1, "SHA1");
}
private Context mContext;
private LayoutInflater mInflater;
private DownloadManager mManager;
private DownloadManagerService.DMBinder mBinder;
private int mLayout;
public MissionAdapter(Context context, DownloadManagerService.DMBinder binder, DownloadManager manager, boolean isLinear) {
mContext = context;
mManager = manager;
mBinder = binder;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLayout = isLinear ? R.layout.mission_item_linear : R.layout.mission_item;
}
@Override
public MissionAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final ViewHolder h = new ViewHolder(mInflater.inflate(mLayout, parent, false));
h.menu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buildPopup(h);
}
});
/*h.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDetail(h);
}
});*/
return h;
}
@Override
public void onViewRecycled(MissionAdapter.ViewHolder h) {
super.onViewRecycled(h);
h.mission.removeListener(h.observer);
h.mission = null;
h.observer = null;
h.progress = null;
h.position = -1;
h.lastTimeStamp = -1;
h.lastDone = -1;
h.colorId = 0;
}
@Override
public void onBindViewHolder(MissionAdapter.ViewHolder h, int pos) {
DownloadMission ms = mManager.getMission(pos);
h.mission = ms;
h.position = pos;
Utility.FileType type = Utility.getFileType(ms.name);
h.icon.setImageResource(Utility.getIconForFileType(type));
h.name.setText(ms.name);
h.size.setText(Utility.formatBytes(ms.length));
h.progress = new ProgressDrawable(mContext, Utility.getBackgroundForFileType(type), Utility.getForegroundForFileType(type));
h.bkg.setBackgroundDrawable(h.progress);
h.observer = new MissionObserver(this, h);
ms.addListener(h.observer);
updateProgress(h);
}
@Override
public int getItemCount() {
return mManager.getCount();
}
@Override
public long getItemId(int position) {
return position;
}
private void updateProgress(ViewHolder h) {
updateProgress(h, false);
}
private void updateProgress(ViewHolder h, boolean finished) {
if (h.mission == null) return;
long now = System.currentTimeMillis();
if (h.lastTimeStamp == -1) {
h.lastTimeStamp = now;
}
if (h.lastDone == -1) {
h.lastDone = h.mission.done;
}
long deltaTime = now - h.lastTimeStamp;
long deltaDone = h.mission.done - h.lastDone;
if (deltaTime == 0 || deltaTime > 1000 || finished) {
if (h.mission.errCode > 0) {
h.status.setText(R.string.msg_error);
} else {
float progress = (float) h.mission.done / h.mission.length;
h.status.setText(String.format(Locale.US, "%.2f%%", progress * 100));
h.progress.setProgress(progress);
}
}
if (deltaTime > 1000 && deltaDone > 0) {
float speed = (float) deltaDone / deltaTime;
String speedStr = Utility.formatSpeed(speed * 1000);
String sizeStr = Utility.formatBytes(h.mission.length);
h.size.setText(sizeStr + " " + speedStr);
h.lastTimeStamp = now;
h.lastDone = h.mission.done;
}
}
private void buildPopup(final ViewHolder h) {
PopupMenu popup = new PopupMenu(mContext, h.menu);
popup.inflate(R.menu.mission);
Menu menu = popup.getMenu();
MenuItem start = menu.findItem(R.id.start);
MenuItem pause = menu.findItem(R.id.pause);
MenuItem view = menu.findItem(R.id.view);
MenuItem delete = menu.findItem(R.id.delete);
MenuItem checksum = menu.findItem(R.id.checksum);
// Set to false first
start.setVisible(false);
pause.setVisible(false);
view.setVisible(false);
delete.setVisible(false);
checksum.setVisible(false);
if (!h.mission.finished) {
if (!h.mission.running) {
if (h.mission.errCode == -1) {
start.setVisible(true);
}
delete.setVisible(true);
} else {
pause.setVisible(true);
}
} else {
view.setVisible(true);
delete.setVisible(true);
checksum.setVisible(true);
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.start:
mManager.resumeMission(h.position);
mBinder.onMissionAdded(mManager.getMission(h.position));
return true;
case R.id.pause:
mManager.pauseMission(h.position);
mBinder.onMissionRemoved(mManager.getMission(h.position));
h.lastTimeStamp = -1;
h.lastDone = -1;
return true;
case R.id.view:
File f = new File(h.mission.location, h.mission.name);
String ext = Utility.getFileExt(h.mission.name);
Log.d(TAG, "Viewing file: " + f.getAbsolutePath() + " ext: " + ext);
if (ext == null) {
Log.w(TAG, "Can't view file because it has no extension: " +
h.mission.name);
return false;
}
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.substring(1));
Log.v(TAG, "Mime: " + mime + " package: " + mContext.getApplicationContext().getPackageName() + ".provider");
if (f.exists()) {
viewFileWithFileProvider(f, mime);
} else {
Log.w(TAG, "File doesn't exist");
}
return true;
case R.id.delete:
mManager.deleteMission(h.position);
notifyDataSetChanged();
return true;
case R.id.md5:
case R.id.sha1:
DownloadMission mission = mManager.getMission(h.position);
new ChecksumTask().execute(mission.location + "/" + mission.name, ALGORITHMS.get(id));
return true;
default:
return false;
}
}
});
popup.show();
}
private void viewFile(File file, String mimetype) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), mimetype);
intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(FLAG_GRANT_PREFIX_URI_PERMISSION);
}
//mContext.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.v(TAG, "Starting intent: " + intent);
mContext.startActivity(intent);
}
private void viewFileWithFileProvider(File file, String mimetype) {
String ourPackage = mContext.getApplicationContext().getPackageName();
Uri uri = FileProvider.getUriForFile(mContext, ourPackage + ".provider", file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, mimetype);
intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(FLAG_GRANT_PREFIX_URI_PERMISSION);
}
//mContext.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.v(TAG, "Starting intent: " + intent);
mContext.startActivity(intent);
}
private class ChecksumTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create dialog
prog = new ProgressDialog(mContext);
prog.setCancelable(false);
prog.setMessage(mContext.getString(R.string.msg_wait));
prog.show();
}
@Override
protected String doInBackground(String... params) {
return Utility.checksum(params[0], params[1]);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
Utility.copyToClipboard(mContext, result);
}
}
static class ViewHolder extends RecyclerView.ViewHolder {
public DownloadMission mission;
public int position;
public TextView status;
public ImageView icon;
public TextView name;
public TextView size;
public View bkg;
public ImageView menu;
public ProgressDrawable progress;
public MissionObserver observer;
public long lastTimeStamp = -1;
public long lastDone = -1;
public int colorId;
public ViewHolder(View v) {
super(v);
status = Utility.findViewById(v, R.id.item_status);
icon = Utility.findViewById(v, R.id.item_icon);
name = Utility.findViewById(v, R.id.item_name);
size = Utility.findViewById(v, R.id.item_size);
bkg = Utility.findViewById(v, R.id.item_bkg);
menu = Utility.findViewById(v, R.id.item_more);
}
}
static class MissionObserver implements DownloadMission.MissionListener {
private MissionAdapter mAdapter;
private ViewHolder mHolder;
public MissionObserver(MissionAdapter adapter, ViewHolder holder) {
mAdapter = adapter;
mHolder = holder;
}
@Override
public void onProgressUpdate(DownloadMission downloadMission, long done, long total) {
mAdapter.updateProgress(mHolder);
}
@Override
public void onFinish(DownloadMission downloadMission) {
//mAdapter.mManager.deleteMission(mHolder.position);
// TODO Notification
//mAdapter.notifyDataSetChanged();
if (mHolder.mission != null) {
mHolder.size.setText(Utility.formatBytes(mHolder.mission.length));
mAdapter.updateProgress(mHolder, true);
}
}
@Override
public void onError(DownloadMission downloadMission, int errCode) {
mAdapter.updateProgress(mHolder);
}
}
}

View File

@@ -0,0 +1,58 @@
package us.shandian.giga.ui.common;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
public class ProgressDrawable extends Drawable
{
private float mProgress;
private int mBackgroundColor, mForegroundColor;
public ProgressDrawable(Context context, int background, int foreground) {
this(context.getResources().getColor(background), context.getResources().getColor(foreground));
}
public ProgressDrawable(int background, int foreground) {
mBackgroundColor = background;
mForegroundColor = foreground;
}
public void setProgress(float progress) {
mProgress = progress;
invalidateSelf();
}
@Override
public void draw(Canvas canvas) {
int width = canvas.getWidth();
int height = canvas.getHeight();
Paint paint = new Paint();
paint.setColor(mBackgroundColor);
canvas.drawRect(0, 0, width, height, paint);
paint.setColor(mForegroundColor);
canvas.drawRect(0, 0, (int) (mProgress * width), height, paint);
}
@Override
public void setAlpha(int alpha) {
// Unsupported
}
@Override
public void setColorFilter(ColorFilter filter) {
// Unsupported
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}

View File

@@ -0,0 +1,26 @@
package us.shandian.giga.ui.common;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import org.schabi.newpipe.R;
import us.shandian.giga.util.Utility;
public abstract class ToolbarActivity extends ActionBarActivity
{
protected Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
mToolbar = Utility.findViewById(this, R.id.toolbar);
setSupportActionBar(mToolbar);
}
protected abstract int getLayoutResource();
}

View File

@@ -0,0 +1,13 @@
package us.shandian.giga.ui.fragment;
import us.shandian.giga.get.DownloadManager;
import us.shandian.giga.service.DownloadManagerService;
public class AllMissionsFragment extends MissionsFragment
{
@Override
protected DownloadManager setupDownloadManager(DownloadManagerService.DMBinder binder) {
return binder.getDownloadManager();
}
}

View File

@@ -0,0 +1,148 @@
package us.shandian.giga.ui.fragment;
import android.app.Activity;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import org.schabi.newpipe.R;
import us.shandian.giga.get.DownloadManager;
import us.shandian.giga.service.DownloadManagerService;
import us.shandian.giga.ui.adapter.MissionAdapter;
import us.shandian.giga.util.Utility;
public abstract class MissionsFragment extends Fragment
{
private DownloadManager mManager;
private DownloadManagerService.DMBinder mBinder;
private SharedPreferences mPrefs;
private boolean mLinear;
private MenuItem mSwitch;
private RecyclerView mList;
private MissionAdapter mAdapter;
private GridLayoutManager mGridManager;
private LinearLayoutManager mLinearManager;
private Context mActivity;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
mBinder = (DownloadManagerService.DMBinder) binder;
mManager = setupDownloadManager(mBinder);
updateList();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// What to do?
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.missions, container, false);
mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
mLinear = mPrefs.getBoolean("linear", false);
// Bind the service
Intent i = new Intent();
i.setClass(getActivity(), DownloadManagerService.class);
getActivity().bindService(i, mConnection, Context.BIND_AUTO_CREATE);
// Views
mList = Utility.findViewById(v, R.id.mission_recycler);
// Init
mGridManager = new GridLayoutManager(getActivity(), 2);
mLinearManager = new LinearLayoutManager(getActivity());
mList.setLayoutManager(mGridManager);
setHasOptionsMenu(true);
return v;
}
/** Added in API level 23. */
@Override
public void onAttach(Context activity) {
super.onAttach(activity);
// Bug: in api< 23 this is never called
// so mActivity=null
// so app crashes with nullpointer exception
mActivity = activity;
}
/** deprecated in API level 23,
* but must remain to allow compatibility with api<23 */
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
@Override
public void onDestroyView() {
super.onDestroyView();
getActivity().unbindService(mConnection);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.switch_mode:
mLinear = !mLinear;
updateList();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void notifyChange() {
mAdapter.notifyDataSetChanged();
}
private void updateList() {
mAdapter = new MissionAdapter(mActivity, mBinder, mManager, mLinear);
if (mLinear) {
mList.setLayoutManager(mLinearManager);
} else {
mList.setLayoutManager(mGridManager);
}
mList.setAdapter(mAdapter);
if (mSwitch != null) {
mSwitch.setIcon(mLinear ? R.drawable.grid : R.drawable.list);
}
mPrefs.edit().putBoolean("linear", mLinear).commit();
}
protected abstract DownloadManager setupDownloadManager(DownloadManagerService.DMBinder binder);
}

View File

@@ -0,0 +1,85 @@
package us.shandian.giga.util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Environment;
import java.io.File;
import java.io.PrintWriter;
//todo: replace this by using the internal crash handler of newpipe
public class CrashHandler implements Thread.UncaughtExceptionHandler
{
public static final String CRASH_DIR = Environment.getExternalStorageDirectory().getPath() + "/GigaCrash/";
public static final String CRASH_LOG = CRASH_DIR + "last_crash.log";
public static final String CRASH_TAG = CRASH_DIR + ".crashed";
private static String ANDROID = Build.VERSION.RELEASE;
private static String MODEL = Build.MODEL;
private static String MANUFACTURER = Build.MANUFACTURER;
public static String VERSION = "Unknown";
private Thread.UncaughtExceptionHandler mPrevious;
public static void init(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
VERSION = info.versionName + info.versionCode;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void register() {
new CrashHandler();
}
private CrashHandler() {
mPrevious = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread().setUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
File f = new File(CRASH_LOG);
if (f.exists()) {
f.delete();
} else {
try {
new File(CRASH_DIR).mkdirs();
f.createNewFile();
} catch (Exception e) {
return;
}
}
PrintWriter p;
try {
p = new PrintWriter(f);
} catch (Exception e) {
return;
}
p.write("Android Version: " + ANDROID + "\n");
p.write("Device Model: " + MODEL + "\n");
p.write("Device Manufacturer: " + MANUFACTURER + "\n");
p.write("App Version: " + VERSION + "\n");
p.write("*********************\n");
throwable.printStackTrace(p);
p.close();
try {
new File(CRASH_TAG).createNewFile();
} catch (Exception e) {
return;
}
if (mPrevious != null) {
mPrevious.uncaughtException(thread, throwable);
}
}
}

Some files were not shown because too many files have changed in this diff Show More