summaryrefslogtreecommitdiffstats
path: root/comedyGenerator
blob: e2acc2f01835d30d86fba1fa3b8bb4d908458a0f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/python3
import requests
import urllib.request
import os
import argparse
import time
import hashlib
import configparser
from multiprocessing import Pool
import xdg
import configparser
import os 

config = configparser.ConfigParser()
configdir = str(xdg.XDG_CONFIG_HOME)
config.read(configdir + "/comedyGenerator")

parser = argparse.ArgumentParser(add_help=True)

parser.add_argument('--verbose', '-v',
        default=False,
        action='store_true',
        dest='verbose',
        help='Enables verbose output'
        )

parser.add_argument('--amount','-a',
        default=10,
        dest='amount',
        action="store",
        help="the amount of funnies you'd like to download per tag",
        type=int
        )

parser.add_argument('--output','-o',
        default=config['DEFAULT']['output'],
        dest='output',
        action="store",
        help="the output directory of the funnies",
        type=str
        )

parser.add_argument('--log','-l',
        default=config['DEFAULT']['log'],
        dest='log',
        action="store",
        help="the output directory of the log file for your funnies",
        type=str
        )

parser.add_argument('--jobs','-j',
        default=1,
        dest='jobs',
        action="store",
        help="how many jobs you'd like to use while downloading",
        type=int
        )

parser.add_argument('tags',
        nargs='+',
        type=str,
        help='Provides tags to be check for funny downloading'
        )

args = parser.parse_args()

#string comparision so I don't need two vars; bloat kills bloat
logging = False
if not args.log == "False":
    logging = True
    logFile = open(args.log, "a")
    tmpLog = []
    if args.verbose:
        print("We're going to be logging!")
        print("Logging Path: " + args.log)

headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.5",
        "DNT": "1",
        "Connection": "keep-alive",
        "Upgrade-Insecure-Requests": "1",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "cross-site",
        "Cache-Control": "max-age=0"
        }

for tags in args.tags:
        videos = []
        print("Downloading Tag: " + tags)
        headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
                "DNT": "1",
                "Connection": "keep-alive",
                "Upgrade-Insecure-Requests": "1",
                "Sec-Fetch-Dest": "document",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "cross-site",
                "Cache-Control": "max-age=0"
            }
        
        for tries in range(100):
            try:
                master = requests.get('https://ifunny.co/', headers=headers)
            except:
                if tries < 100 - 1:
                    print("Rate Limited! Sleeping for " + str(tries*1.5) + " seconds!")
                    time.sleep(tries*1.5)
                    continue
            break
        combineHeader = (dict(master.headers)|headers)
        requestHeader = {
                "User-Agent":combineHeader['User-Agent'],
                "Content-Type":combineHeader['Content-Type'],
                "x-requested-with": "fetch",
                "x-csrf-token": combineHeader['Set-Cookie'].split(';')[0].split('=')[1],
                "set-cookies":combineHeader['Set-Cookie'],
                "access-control-allow-headers":combineHeader['access-control-allow-headers']
                }
        requestCookies = {
                "CID" : combineHeader['Set-Cookie'].split(';')[3].split('=')[2],
                "sound" : "off",
                "viewMode" : "list",
                "x-csrf-token": combineHeader['Set-Cookie'].split(';')[0].split('=')[1]
                }
        for tries in range(100):
            try:
                tagPage = requests.get("https://ifunny.co/api/v1/feeds?filter=video&tag=" + tags, headers=requestHeader, cookies=requestCookies)
                if args.verbose:
                    print("Got Webpage!")
            except:
                if tries < 100 - 1:
                    print("Rate Limited! Sleeping for " + str(tries*1.5) + " seconds!")
                    time.sleep(tries*1.5)
                    continue
            break

        JSONDump = tagPage.json()
        while len(videos) < args.amount and len(JSONDump['items']) > 0:
            print("Currently have " + str(len(videos)) + " videos out of " + str(args.amount) + " (" + str((len(videos)/args.amount)*100) + "%)")
            for item in range(len(JSONDump['items'])):
                videos.append(JSONDump['items'][item]['url'])
            for tries in range(100):
                try:
                    tagPage = requests.get("https://ifunny.co/api/v1/feeds?filter=video&tag=" + tags + "&next=" + JSONDump['pagination']['next'], headers=requestHeader, cookies=requestCookies)
                    JSONDump = tagPage.json()
                    if args.verbose:
                        print("Got New Tag Page!")
                    break
                except:
                    if tries < 100 - 1:
                        print("Rate Limited! Sleeping for " + str(tries*1.5) + " seconds!")
                        time.sleep(tries*1.5)
                        continue
        if len(videos) > args.amount:
            videos = videos[:args.amount]
            if args.verbose:
                print("Videos list truncated! Its now: " + str(len(videos)) + " units long")

        def download(video):
            if args.verbose:
                print("Now running for " + str(video))
            name = tags + "-" + hashlib.md5(video.encode('utf-8')).hexdigest() + ".mp4"
            outputPath = args.output + name
            if args.verbose:
                print("name read as: " + name)
            if os.path.exists(outputPath):
                print(name + " already exists!")
            else:
                print("saving " + video + " as " + name)
                for tries in range(100):
                    try:
                        urllib.request.urlretrieve(video, outputPath) 
                    except:
                        if tries < 100 - 1:
                            print("Rate Limited! Sleeping for " + str(tries*1.5) + " seconds!")
                            time.sleep(tries*1.5)
                        continue
                    break
        if args.jobs > 1:
            pool = Pool(args.jobs)
            for video in videos:
                pool.apply_async(download, (video,))
            pool.close()
            pool.join()
            if logging:
                for video in videos:
                    logName = tags + "-" + hashlib.md5(video.encode('utf-8')).hexdigest() + ".mp4"
                    logPath = args.output + logName
                    if args.verbose:
                        print("Writing " + logPath + " to log file")
                    logFile.write(logPath + "\n")
                logFile.close()
        else:
            for video in videos:
                download(video)
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License version 3 as published by
#the Free Software Foundation.
#
#This program 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 Affero General Public License for more details.
#
#You should have received a copy of the GNU Affero General Public License
#along with this program.  If not, see <https://www.gnu.org/licenses/>.