Skip to content

Commit

Permalink
feat: python cookiejar
Browse files Browse the repository at this point in the history
  • Loading branch information
thewh1teagle committed Sep 30, 2023
1 parent 1b1583d commit e06c2d5
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 6 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
target/
Cargo.lock
Cargo.lock
__pycache__
*.pyc
54 changes: 54 additions & 0 deletions bindings/python/rookiepy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from .rookiepy import firefox, brave, edge, chrome, chromium_based
from typing import List, Any
import http.cookiejar


__all__ = [
"firefox",
"brave",
"edge",
"chrome",
"chromium_based",
"to_dict",
"to_cookiejar",
"create_cookie"
]

def create_cookie(host, path, secure, expires, name, value, http_only):
"""Shortcut function to create a cookie"""
# HTTPOnly flag goes in _rest, if present (see https://github.com/python/cpython/pull/17471/files#r511187060)
return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path,
True, secure, expires, False, None, None,
{'HTTPOnly': ''} if http_only else {})


def to_dict(cookies: List[Any]):
return [
{'name': c.name,
'host': c.host,
'path': c.path,
'secure': c.secure,
'expires': c.expires,
'value': c.value,
'http_only': c.http_only,
'same_site': c.same_site
}
for c in cookies
]

def to_cookiejar(cookies: List[Any]):
cj = http.cookiejar.CookieJar()

for cookie_obj in cookies:
c = create_cookie(
cookie_obj.host,
cookie_obj.path,
cookie_obj.secure,
cookie_obj.expires,
cookie_obj.name,
cookie_obj.value,
cookie_obj.http_only,

)
cj.set_cookie(c)
return cj
14 changes: 10 additions & 4 deletions bindings/python/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@

use std::{fmt::{self}, time::SystemTime, path::PathBuf};
use rookie::{self, enums::{CookieToString,Cookie}};
use pyo3::types::{PyFloat, PyString, PyList};
use pyo3::types::{PyFloat, PyString, PyList, PyDict};
use pyo3::exceptions::{PyTypeError, PyKeyError};

use pyo3::prelude::*;


Expand Down Expand Up @@ -29,11 +31,15 @@ impl PyCookie {
fn secure(&self) -> bool {
self.inner.secure
}

#[getter]
fn expires(&self) -> PyResult<String> {
fn expires(&self) -> PyResult<u128> {
match self.inner.expires.duration_since(SystemTime::UNIX_EPOCH) {
Ok(duration) => Ok(duration.as_secs().to_string()),
Err(_) => Ok("Invalid duration".to_string())
Ok(duration) => {
let ms = duration.as_millis();
Ok(ms)
}
Err(_) => Ok(0)
}
}

Expand Down
34 changes: 34 additions & 0 deletions examples/http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import requests
import re
from rookiepy import brave, to_cookiejar
import browser_cookie3

def extract_username(html):
re_pattern = r'dashboard/ajax_context_list\?current_context=(.+)'
match = re.search(re_pattern, html)
if match:
return match.group(1)
return ""


def main():
try:
# Create a custom cookie store
cookies = brave(["github.com"])
cj = to_cookiejar(cookies)

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36",
}
response = requests.get("https://github.com/", cookies=cj, headers=headers)
content = response.text
username = extract_username(content)
if not username:
print("Not logged in to Github")
else:
print(f"Logged in to Github as {username}")

except Exception as e:
print(f"An error occurred: {e}")

main()
2 changes: 1 addition & 1 deletion rookie-rs/bin/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use rookie;

fn main() {
let cookies = rookie::firefox(Some(vec!["google.com"])).unwrap();
let cookies = rookie::brave(Some(vec!["github.com"])).unwrap();
println!("{:?}", cookies);
}

0 comments on commit e06c2d5

Please sign in to comment.