dotfiles

<-- duh.
git clone https://hhvn.uk/dotfiles
git clone git://hhvn.uk/dotfiles
Log | Files | Refs | Submodules | LICENSE

sponsorblock.py (5261B)


      1 # GPLv3
      2 
      3 import urllib.request
      4 import urllib.parse
      5 import hashlib
      6 import sqlite3
      7 import random
      8 import string
      9 import json
     10 import sys
     11 import os
     12 
     13 if sys.argv[1] in ["submit", "stats", "username"]:
     14     if not sys.argv[8]:
     15         if os.path.isfile(sys.argv[7]):
     16             with open(sys.argv[7]) as f:  
     17                 uid = f.read()
     18         else:
     19             uid = "".join(random.choices(string.ascii_letters + string.digits, k=36))
     20             with open(sys.argv[7], "w") as f:
     21                 f.write(uid)
     22     else:
     23         uid = sys.argv[8]
     24 
     25 opener = urllib.request.build_opener()
     26 opener.addheaders = [("User-Agent", "mpv_sponsorblock/1.0 (https://github.com/po5/mpv_sponsorblock)")]
     27 urllib.request.install_opener(opener)
     28 
     29 if sys.argv[1] == "ranges" and (not sys.argv[2] or not os.path.isfile(sys.argv[2])):
     30     sha = None
     31     if 3 <= int(sys.argv[6]) <= 32:
     32         sha = hashlib.sha256(sys.argv[4].encode()).hexdigest()[:int(sys.argv[6])]
     33     times = []
     34     try:
     35         response = urllib.request.urlopen(sys.argv[3] + "/api/skipSegments" + ("/" + sha + "?" if sha else "?videoID=" + sys.argv[4] + "&") + urllib.parse.urlencode([("categories", json.dumps(sys.argv[5].split(",")))]))
     36         segments = json.load(response)
     37         for segment in segments:
     38             if sha and sys.argv[4] != segment["videoID"]:
     39                 continue
     40             if sha:
     41                 for s in segment["segments"]:
     42                     times.append(str(s["segment"][0]) + "," + str(s["segment"][1]) + "," + s["UUID"] + "," + s["category"])
     43             else:
     44                 times.append(str(segment["segment"][0]) + "," + str(segment["segment"][1]) + "," + segment["UUID"] + "," + segment["category"])
     45         print(":".join(times))
     46     except (TimeoutError, urllib.error.URLError) as e:
     47         print("error")
     48     except urllib.error.HTTPError as e:
     49         if e.code == 404:
     50             print("")
     51         else:
     52             print("error")
     53 elif sys.argv[1] == "ranges":
     54     conn = sqlite3.connect(sys.argv[2])
     55     conn.row_factory = sqlite3.Row
     56     c = conn.cursor()
     57     times = []
     58     for category in sys.argv[5].split(","):
     59         c.execute("SELECT startTime, endTime, votes, UUID, category FROM sponsorTimes WHERE videoID = ? AND shadowHidden = 0 AND votes > -1 AND category = ?", (sys.argv[4], category))
     60         sponsors = c.fetchall()
     61         best = list(sponsors)
     62         dealtwith = []
     63         similar = []
     64         for sponsor_a in sponsors:
     65             for sponsor_b in sponsors:
     66                 if sponsor_a is not sponsor_b and sponsor_a["startTime"] >= sponsor_b["startTime"] and sponsor_a["startTime"] <= sponsor_b["endTime"]:
     67                     similar.append([sponsor_a, sponsor_b])
     68                     if sponsor_a in best:
     69                         best.remove(sponsor_a)
     70                     if sponsor_b in best:
     71                         best.remove(sponsor_b)
     72         for sponsors_a in similar:
     73             if sponsors_a in dealtwith:
     74                 continue
     75             group = set(sponsors_a)
     76             for sponsors_b in similar:
     77                 if sponsors_b[0] in group or sponsors_b[1] in group:
     78                     group.add(sponsors_b[0])
     79                     group.add(sponsors_b[1])
     80                     dealtwith.append(sponsors_b)
     81             best.append(max(group, key=lambda x:x["votes"]))
     82         for time in best:
     83             times.append(str(time["startTime"]) + "," + str(time["endTime"]) + "," + time["UUID"] + "," + time["category"])
     84     print(":".join(times))
     85 elif sys.argv[1] == "update":
     86     try:
     87         urllib.request.urlretrieve(sys.argv[3] + "/database.db", sys.argv[2] + ".tmp")
     88         os.replace(sys.argv[2] + ".tmp", sys.argv[2])
     89     except PermissionError:
     90         print("database update failed, file currently in use", file=sys.stderr)
     91         sys.exit(1)
     92     except ConnectionResetError:
     93         print("database update failed, connection reset", file=sys.stderr)
     94         sys.exit(1)
     95     except TimeoutError:
     96         print("database update failed, timed out", file=sys.stderr)
     97         sys.exit(1)
     98     except urllib.error.URLError:
     99         print("database update failed", file=sys.stderr)
    100         sys.exit(1)
    101 elif sys.argv[1] == "submit":
    102     try:
    103         req = urllib.request.Request(sys.argv[3] + "/api/skipSegments", data=json.dumps({"videoID": sys.argv[4], "segments": [{"segment": [float(sys.argv[5]), float(sys.argv[6])], "category": sys.argv[9]}], "userID": uid}).encode(), headers={"Content-Type": "application/json"})
    104         response = urllib.request.urlopen(req)
    105         print("success")
    106     except urllib.error.HTTPError as e:
    107         print(e.code)
    108     except:
    109         print("error")
    110 elif sys.argv[1] == "stats":
    111     try:
    112         if sys.argv[6]:
    113             urllib.request.urlopen(sys.argv[3] + "/api/viewedVideoSponsorTime?UUID=" + sys.argv[5])
    114         if sys.argv[9]:
    115             urllib.request.urlopen(sys.argv[3] + "/api/voteOnSponsorTime?UUID=" + sys.argv[5] + "&userID=" + uid + "&type=" + sys.argv[9])
    116     except:
    117         pass
    118 elif sys.argv[1] == "username":
    119     try:
    120         data = urllib.parse.urlencode({"userID": uid, "userName": sys.argv[9]}).encode()
    121         req = urllib.request.Request(sys.argv[3] + "/api/setUsername", data=data)
    122         urllib.request.urlopen(req)
    123     except:
    124         pass