about summary refs log tree commit diff
path: root/pkgs/games/humblebundle/fetch-humble-bundle/default.nix
blob: 8431799bbc0302d7b93cfe631df069facf81550b (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
{ stdenv, curl, cacert, writeText, fetchFromGitHub, fetchpatch
, python, pythonPackages

# Dependencies for the captcha solver
, pkgconfig, qt5, runCommandCC

, email, password
}:

{ name ? null, machineName, downloadName ? "Download", suffix ? "humblebundle", md5 }: let
  cafile = "${cacert}/etc/ssl/certs/ca-bundle.crt";

  getCaptcha = let
    injectedJS = ''
      function waitForResponse() {
        try {
          var response = grecaptcha.getResponse();
        } catch(_) {
          return setTimeout(waitForResponse, 50);
        }
        if (response != "")
          document.title = response;
        else
          setTimeout(waitForResponse, 50);
      }

      waitForResponse();
    '';

    escapeCString = stdenv.lib.replaceStrings ["\"" "\n"] ["\\\"" "\\n"];

    application = writeText "captcha.cc" ''
      #include <QApplication>
      #include <QWebEngineView>
      #include <QTcpServer>
      #include <QQuickWebEngineProfile>

      int main(int argc, char **argv) {
        QApplication *app = new QApplication(argc, argv);
        QTcpServer *server = new QTcpServer();
        QWebEngineView *browser = new QWebEngineView();

        QQuickWebEngineProfile::defaultProfile()->setOffTheRecord(true);

        if (!server->listen(QHostAddress::LocalHost, 18123)) {
          qCritical() << "Unable to listen on port 18123!";
          return 1;
        }

        qInfo() << "Waiting for connection from the HB downloader...";
        if (!server->waitForNewConnection(-1)) {
          qCritical() << "Unable to accept the connection!";
          return 1;
        }
        qInfo() << "Connection established, spawning window to solve captcha.";

        QTcpSocket *sock = server->nextPendingConnection();

        browser->load(QUrl("https://www.humblebundle.com/user/captcha"));
        browser->show();

        browser->connect(browser, &QWebEngineView::loadFinished, [=]() {
          browser->page()->runJavaScript("${escapeCString injectedJS}");
          browser->connect(
            browser, &QWebEngineView::titleChanged, [=](const QString &title) {
              sock->write(title.toUtf8());
              sock->flush();
              sock->waitForBytesWritten();
              sock->close();
              server->close();
              app->quit();
            }
          );
        });

        return app->exec();
      }
    '';

  in runCommandCC "get-captcha" {
    nativeBuildInputs = [ pkgconfig ];
    buildInputs = [ qt5.qtbase qt5.qtwebengine ];
  } ''
    g++ $(pkg-config --libs --cflags Qt5WebEngineWidgets Qt5WebEngine) \
      -Wall -std=c++11 -o "$out" ${application}
  '';

  humbleAPI = pythonPackages.buildPythonPackage rec {
    name = "humblebundle-${version}";
    version = "0.1.1";

    src = fetchFromGitHub {
      owner = "saik0";
      repo = "humblebundle-python";
      rev = version;
      sha256 = "1kcg42nh7sbjabim1pbqx14468pypznjy7fx2bv7dicy0sqd9b8j";
    };

    postPatch = ''
      sed -i -e '/^LOGIN_URL *=/s,/login,/processlogin,' humblebundle/client.py
    '';

    propagatedBuildInputs = [ pythonPackages.requests ];
  };

  pyStr = str: "'${stdenv.lib.escape ["'" "\\"] str}'";

  getDownloadURL = writeText "gethburl.py" ''
    import socket, sys, time, humblebundle

    def get_products(client):
      gamekeys = client.get_gamekeys()
      for gamekey in gamekeys:
        order = hb.get_order(gamekey)
        if order.subproducts is None:
          continue
        for subproduct in order.subproducts:
          prodname = subproduct.human_name.encode('ascii', 'replace')
          downloads = [(download.machine_name, download.download_struct)
                       for download in subproduct.downloads]
          yield ((subproduct.machine_name, prodname), downloads)

    def find_download(downloads):
      for machine_name, dstruct in sum(downloads.values(), []):
        if machine_name == ${pyStr machineName}:
          for ds in dstruct:
            if ds.name == ${pyStr downloadName}:
              return ds
          print >>sys.stderr, \
            ${pyStr "Unable to find ${downloadName} for ${machineName}!"}
          print >>sys.stderr, 'Available download types:'
          for ds in dstruct:
            print >>sys.stderr, "  " + ds.name
          raise SystemExit(1)

    def login_with_captcha(hb):
      print >>sys.stderr, "Solving a captcha is required to log in."
      print >>sys.stderr, "Please run " ${pyStr (toString getCaptcha)} " now."
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      print >>sys.stderr, "Waiting for connection",
      i = 0
      while sock.connect_ex(("127.0.0.1", 18123)) != 0:
        time.sleep(0.1)
        if i % 10 == 0:
          sys.stderr.write('.')
          sys.stderr.flush()
        i += 1
      print >>sys.stderr, " connected."
      print >>sys.stderr, "Waiting for captcha to be solved..."
      response = sock.recv(4096)
      sock.close()
      print >>sys.stderr, "Captcha solved correctly, logging in."
      hb.login(${pyStr email}, ${pyStr password}, recaptcha_response=response)

    hb = humblebundle.HumbleApi()
    try:
      hb.login(${pyStr email}, ${pyStr password})
    except humblebundle.exceptions.HumbleCaptchaException:
      login_with_captcha(hb)

    products = dict(get_products(hb))
    dstruct = find_download(products)

    if dstruct is None:
      print >>sys.stderr, ${pyStr "Cannot find download for ${machineName}!"}
      print >>sys.stderr, 'Available machine names:'
      for name, dstructs in sorted(products.items(), key=lambda x: x[0]):
        print >>sys.stderr, "  * " + name[1]
        print >>sys.stderr, "    " + ', '.join(map(lambda x: x[0], dstructs))
      raise SystemExit(1)
    elif dstruct.md5 != ${pyStr md5}:
      print >>sys.stderr, \
        ${pyStr "MD5 for ${machineName} is not ${md5} but "} \
        + dstruct.md5 + '.'
      raise SystemExit(1)
    else:
      print dstruct.url.web
  '';
in stdenv.mkDerivation {
  name = if name != null then name else "${machineName}.${suffix}";
  outputHashAlgo = "md5";
  outputHash = md5;

  buildInputs = [ python humbleAPI ];

  buildCommand = ''
    url="$(python "${getDownloadURL}")"
    header "downloading $name from $url"
    "${curl.bin or curl}/bin/curl" --cacert "${cafile}" --fail \
      --output "$out" "$url"
    stopNest
  '';
}