File size: 14,099 Bytes
34367da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python3
"""
πŸͺ Scribd Cookie Extractor - Valideret Metode
=============================================

Ekstraherer _scribd_session og _scribd_expire cookies fra Chrome
ved at bruge din eksisterende Google OAuth login.

Metode 1: browser_cookie3 (hurtigst - læser direkte fra Chrome DB)
Metode 2: Selenium med Chrome profil (fallback - starter browser)
Metode 3: Manuel cookie input (hvis alt andet fejler)

@author WidgeTDC Neural Network
"""

import os
import sys
import json
import sqlite3
import shutil
import tempfile
from pathlib import Path
from datetime import datetime
from typing import Dict, Optional, Tuple
import base64

# Attempt imports
try:
    import browser_cookie3
    HAS_BROWSER_COOKIE3 = True
except ImportError:
    HAS_BROWSER_COOKIE3 = False

try:
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    HAS_SELENIUM = True
except ImportError:
    HAS_SELENIUM = False

try:
    from Crypto.Cipher import AES
    from Crypto.Protocol.KDF import PBKDF2
    import win32crypt
    HAS_CRYPTO = True
except ImportError:
    HAS_CRYPTO = False


class ScribdCookieExtractor:
    """
    Ekstraherer Scribd authentication cookies med multiple metoder
    """
    
    COOKIE_FILE = Path("data/scribd_harvest/scribd_cookies.json")
    REQUIRED_COOKIES = ['_scribd_session', '_scribd_expire']
    
    def __init__(self):
        self.cookies: Dict[str, str] = {}
        self.cookie_file = self.COOKIE_FILE
        self.cookie_file.parent.mkdir(parents=True, exist_ok=True)
    
    def get_cookies(self) -> Dict[str, str]:
        """
        Hent Scribd cookies - prΓΈver alle metoder
        """
        print("πŸͺ Scribd Cookie Extractor")
        print("=" * 50)
        
        # PrΓΈv at loade gemte cookies fΓΈrst
        if self._load_saved_cookies():
            if self._validate_cookies():
                print("βœ… Bruger gemte cookies")
                return self.cookies
        
        # Metode 1: browser_cookie3
        if HAS_BROWSER_COOKIE3:
            print("\nπŸ“‹ Metode 1: browser_cookie3 (Chrome database)")
            if self._extract_with_browser_cookie3():
                if self._validate_cookies():
                    self._save_cookies()
                    return self.cookies
        
        # Metode 2: Direct Chrome SQLite (Windows)
        if sys.platform == 'win32' and HAS_CRYPTO:
            print("\nπŸ“‹ Metode 2: Chrome SQLite direkte lΓ¦sning")
            if self._extract_from_chrome_sqlite():
                if self._validate_cookies():
                    self._save_cookies()
                    return self.cookies
        
        # Metode 3: Selenium med Chrome profil
        if HAS_SELENIUM:
            print("\nπŸ“‹ Metode 3: Selenium med Chrome profil")
            if self._extract_with_selenium():
                if self._validate_cookies():
                    self._save_cookies()
                    return self.cookies
        
        # Metode 4: Manuel input
        print("\nπŸ“‹ Metode 4: Manuel cookie input")
        if self._extract_manual():
            self._save_cookies()
            return self.cookies
        
        print("\n❌ Kunne ikke hente cookies")
        return {}
    
    def _extract_with_browser_cookie3(self) -> bool:
        """Metode 1: Brug browser_cookie3"""
        try:
            # PrΓΈv Chrome
            try:
                cj = browser_cookie3.chrome(domain_name=".scribd.com")
                for cookie in cj:
                    self.cookies[cookie.name] = cookie.value
                    if cookie.name in self.REQUIRED_COOKIES:
                        print(f"   βœ… Fandt: {cookie.name}")
                return bool(self.cookies)
            except Exception as e:
                print(f"   ⚠️  Chrome: {e}")
            
            # PrΓΈv Edge
            try:
                cj = browser_cookie3.edge(domain_name=".scribd.com")
                for cookie in cj:
                    self.cookies[cookie.name] = cookie.value
                return bool(self.cookies)
            except Exception as e:
                print(f"   ⚠️  Edge: {e}")
            
            return False
        except Exception as e:
            print(f"   ❌ browser_cookie3 fejlede: {e}")
            return False
    
    def _extract_from_chrome_sqlite(self) -> bool:
        """Metode 2: Læs direkte fra Chrome SQLite database (Windows)"""
        try:
            # Find Chrome profil
            local_app_data = os.environ.get('LOCALAPPDATA', '')
            chrome_path = Path(local_app_data) / "Google" / "Chrome" / "User Data"
            
            if not chrome_path.exists():
                print(f"   ⚠️  Chrome profil ikke fundet: {chrome_path}")
                return False
            
            # Kopier cookies database (Chrome lΓ₯ser den)
            cookies_db = chrome_path / "Default" / "Network" / "Cookies"
            if not cookies_db.exists():
                cookies_db = chrome_path / "Default" / "Cookies"
            
            if not cookies_db.exists():
                print(f"   ⚠️  Cookies database ikke fundet")
                return False
            
            # Kopier til temp fil
            temp_db = Path(tempfile.gettempdir()) / "scribd_cookies_temp.db"
            shutil.copy2(cookies_db, temp_db)
            
            # Hent encryption key
            local_state_path = chrome_path / "Local State"
            key = self._get_chrome_encryption_key(local_state_path)
            
            # Læs cookies
            conn = sqlite3.connect(str(temp_db))
            cursor = conn.cursor()
            
            cursor.execute("""
                SELECT name, encrypted_value, host_key 
                FROM cookies 
                WHERE host_key LIKE '%scribd.com%'
            """)
            
            for name, encrypted_value, host in cursor.fetchall():
                try:
                    if key:
                        decrypted = self._decrypt_chrome_cookie(encrypted_value, key)
                        if decrypted:
                            self.cookies[name] = decrypted
                            if name in self.REQUIRED_COOKIES:
                                print(f"   βœ… Dekrypteret: {name}")
                except Exception as e:
                    pass
            
            conn.close()
            temp_db.unlink(missing_ok=True)
            
            return bool(self.cookies)
            
        except Exception as e:
            print(f"   ❌ SQLite læsning fejlede: {e}")
            return False
    
    def _get_chrome_encryption_key(self, local_state_path: Path) -> Optional[bytes]:
        """Hent Chrome's encryption key"""
        try:
            with open(local_state_path, 'r', encoding='utf-8') as f:
                local_state = json.load(f)
            
            encrypted_key = base64.b64decode(
                local_state['os_crypt']['encrypted_key']
            )
            # Fjern "DPAPI" prefix
            encrypted_key = encrypted_key[5:]
            
            # Dekrypter med Windows DPAPI
            key = win32crypt.CryptUnprotectData(encrypted_key, None, None, None, 0)[1]
            return key
        except Exception as e:
            print(f"   ⚠️  Kunne ikke hente encryption key: {e}")
            return None
    
    def _decrypt_chrome_cookie(self, encrypted_value: bytes, key: bytes) -> Optional[str]:
        """Dekrypter Chrome cookie værdi"""
        try:
            if encrypted_value[:3] == b'v10' or encrypted_value[:3] == b'v11':
                # AES-GCM decryption
                nonce = encrypted_value[3:15]
                ciphertext = encrypted_value[15:]
                cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
                decrypted = cipher.decrypt(ciphertext)
                # Fjern authentication tag (sidste 16 bytes)
                return decrypted[:-16].decode('utf-8')
            else:
                # Gammel DPAPI encryption
                return win32crypt.CryptUnprotectData(encrypted_value, None, None, None, 0)[1].decode('utf-8')
        except:
            return None


    def _extract_with_selenium(self) -> bool:
        """Metode 3: Brug Selenium med eksisterende Chrome profil"""
        try:
            # Find Chrome profil
            local_app_data = os.environ.get('LOCALAPPDATA', '')
            chrome_profile = Path(local_app_data) / "Google" / "Chrome" / "User Data"
            
            options = Options()
            options.add_argument(f"--user-data-dir={chrome_profile}")
            options.add_argument("--profile-directory=Default")
            options.add_argument("--no-first-run")
            options.add_argument("--no-default-browser-check")
            # IKKE headless - vi vil bruge eksisterende session
            
            print("   🌐 Γ…bner Chrome med din profil...")
            print("   ⏳ Venter pΓ₯ at Scribd loader...")
            
            driver = webdriver.Chrome(options=options)
            
            try:
                # GΓ₯ til Scribd for at sikre cookies er sat
                driver.get("https://www.scribd.com/")
                
                # Vent pΓ₯ at siden loader
                WebDriverWait(driver, 10).until(
                    EC.presence_of_element_located((By.TAG_NAME, "body"))
                )
                
                # Hent alle cookies
                selenium_cookies = driver.get_cookies()
                
                for cookie in selenium_cookies:
                    self.cookies[cookie['name']] = cookie['value']
                    if cookie['name'] in self.REQUIRED_COOKIES:
                        print(f"   βœ… Fandt: {cookie['name']}")
                
                return bool(self.cookies)
                
            finally:
                driver.quit()
                
        except Exception as e:
            print(f"   ❌ Selenium fejlede: {e}")
            return False
    
    def _extract_manual(self) -> bool:
        """Metode 4: Manuel cookie input fra bruger"""
        print("""
╔══════════════════════════════════════════════════════════════════╗
β•‘  MANUEL COOKIE EXTRACTION                                        β•‘
╠══════════════════════════════════════════════════════════════════╣
β•‘  1. Γ…bn Chrome og gΓ₯ til https://www.scribd.com                  β•‘
β•‘  2. Log ind med din Google konto                                 β•‘
β•‘  3. Tryk F12 for Developer Tools                                 β•‘
β•‘  4. GΓ₯ til Application β†’ Cookies β†’ scribd.com                    β•‘
║  5. Find og kopier værdierne for:                                ║
β•‘     - _scribd_session                                            β•‘
β•‘     - _scribd_expire                                             β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
        """)
        
        try:
            session = input("Indtast _scribd_session værdi: ").strip()
            if not session:
                return False
            
            expire = input("Indtast _scribd_expire værdi (tryk Enter hvis tom): ").strip()
            
            self.cookies['_scribd_session'] = session
            if expire:
                self.cookies['_scribd_expire'] = expire
            
            return True
        except:
            return False
    
    def _validate_cookies(self) -> bool:
        """Valider at vi har de nΓΈdvendige cookies"""
        has_session = '_scribd_session' in self.cookies and self.cookies['_scribd_session']
        if has_session:
            print("   βœ… _scribd_session fundet")
            return True
        print("   ⚠️  Mangler _scribd_session cookie")
        return False
    
    def _save_cookies(self):
        """Gem cookies til fil"""
        data = {
            'cookies': self.cookies,
            'extracted_at': datetime.now().isoformat(),
            'source': 'ScribdCookieExtractor'
        }
        with open(self.cookie_file, 'w') as f:
            json.dump(data, f, indent=2)
        print(f"   πŸ’Ύ Cookies gemt til: {self.cookie_file}")
    
    def _load_saved_cookies(self) -> bool:
        """Load gemte cookies"""
        if not self.cookie_file.exists():
            return False
        try:
            with open(self.cookie_file, 'r') as f:
                data = json.load(f)
            self.cookies = data.get('cookies', {})
            extracted_at = data.get('extracted_at', 'unknown')
            print(f"   πŸ“ Loaded cookies fra: {extracted_at}")
            return bool(self.cookies)
        except:
            return False


def main():
    """Test cookie extraction"""
    extractor = ScribdCookieExtractor()
    cookies = extractor.get_cookies()
    
    if cookies:
        print("\n" + "=" * 50)
        print("βœ… SUCCESS - Cookies ekstraheret!")
        print("=" * 50)
        for name in ['_scribd_session', '_scribd_expire']:
            if name in cookies:
                value = cookies[name]
                print(f"  {name}: {value[:50]}..." if len(value) > 50 else f"  {name}: {value}")
    else:
        print("\n❌ FEJL - Kunne ikke hente cookies")
        print("   PrΓΈv at:")
        print("   1. Luk alle Chrome vinduer")
        print("   2. KΓΈr scriptet igen")
        print("   3. Eller brug manuel input")


if __name__ == "__main__":
    main()