repo
string | commit
string | message
string | diff
string |
---|---|---|---|
arthur-debert/google-code-issues-migrator
|
05b26444e498c2da0890d96be1d040e2fe2f2282
|
Remove number from title of issues posting to Github (sorta redundant given Github's own issue numbering + the already included link to the original google code issue.
|
diff --git a/migrateissues.py b/migrateissues.py
index f8fd794..aa9d221 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,158 +1,158 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from bs4 import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body(self):
return ("_%s - %s_\n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k, v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.find_all('a')[1].string
def get_body(self, node):
return node.find('pre').text
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s\n\nOriginal link: %s" % (soup.find('td', 'vt issuedescription').find('pre').text, self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.find_all('div', "issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.75)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn("skipping issue : %s" % (issue))
except RuntimeError:
- title = "%s - %s " % (issue.id, issue.summary)
+ title = issue.summary
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title=title,
body=issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i, comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
6227c3e57badf86e3a6970e180fbf9f22bf0c66c
|
Turn down Github requests/sec to 0.75 as 0.9 still hit API rate limit eventually.
|
diff --git a/migrateissues.py b/migrateissues.py
index 8e42620..f8fd794 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,158 +1,158 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from bs4 import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body(self):
return ("_%s - %s_\n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k, v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.find_all('a')[1].string
def get_body(self, node):
return node.find('pre').text
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s\n\nOriginal link: %s" % (soup.find('td', 'vt issuedescription').find('pre').text, self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.find_all('div', "issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
- github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.90)
+ github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.75)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn("skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title=title,
body=issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i, comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
721d54cfcf47bdf332264fa792431bd883a7da8a
|
Fix comment body's top line italicization.
|
diff --git a/migrateissues.py b/migrateissues.py
index 823191a..8e42620 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,158 +1,158 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from bs4 import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body(self):
- return ("_%s - %s \n%s_" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
+ return ("_%s - %s_\n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k, v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.find_all('a')[1].string
def get_body(self, node):
return node.find('pre').text
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s\n\nOriginal link: %s" % (soup.find('td', 'vt issuedescription').find('pre').text, self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.find_all('div', "issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.90)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn("skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title=title,
body=issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i, comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
7a49fffd82795151cb836b506497131e615abc65
|
Remove unneeded 'global options'.
|
diff --git a/migrateissues.py b/migrateissues.py
index 3296cfd..823191a 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,159 +1,158 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from bs4 import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body(self):
return ("_%s - %s \n%s_" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k, v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.find_all('a')[1].string
def get_body(self, node):
return node.find('pre').text
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s\n\nOriginal link: %s" % (soup.find('td', 'vt issuedescription').find('pre').text, self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.find_all('div', "issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.90)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn("skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title=title,
body=issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i, comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
- global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
f17ab9b0e556524b5d53858cd95f1cacf1d73b91
|
Set Github requests/sec to 0.90 to try and avoid API rate limit error.
|
diff --git a/migrateissues.py b/migrateissues.py
index 113d0fa..3296cfd 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,159 +1,159 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from bs4 import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body(self):
return ("_%s - %s \n%s_" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k, v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.find_all('a')[1].string
def get_body(self, node):
return node.find('pre').text
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s\n\nOriginal link: %s" % (soup.find('td', 'vt issuedescription').find('pre').text, self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.find_all('div', "issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
- github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.75)
+ github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.90)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn("skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title=title,
body=issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i, comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
f309a4b10f0ba6b2fe6dfd6471c135989c36a81c
|
Removed <pre> around issue text and comment body. Using newlines instead of <br/>. Fix comments so they are actually found in google code issues.
|
diff --git a/migrateissues.py b/migrateissues.py
index 204887e..113d0fa 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,160 +1,159 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from bs4 import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body(self):
return ("_%s - %s \n%s_" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k, v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.find_all('a')[1].string
def get_body(self, node):
- print node.find('pre').text
return node.find('pre').text
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
- self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre'), self.original_url)
+ self.body = "%s\n\nOriginal link: %s" % (soup.find('td', 'vt issuedescription').find('pre').text, self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
- for node in soup.find_all('td', "vt issuecomment"):
+ for node in soup.find_all('div', "issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.75)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn("skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title=title,
body=issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i, comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
2e518362332dc00344ff83cd1cc6db2ff2677e0b
|
Switched to BeautifulSoup4. Improved comment formatting.
|
diff --git a/migrateissues.py b/migrateissues.py
index 2344c53..204887e 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,159 +1,160 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
-from BeautifulSoup import BeautifulSoup
+from bs4 import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body(self):
- return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
+ return ("_%s - %s \n%s_" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k, v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
- return node.findAll('a')[1].string
+ return node.find_all('a')[1].string
def get_body(self, node):
- return node.find('pre').string
+ print node.find('pre').text
+ return node.find('pre').text
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre'), self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
- for node in soup.findAll('td', "vt issuecomment"):
+ for node in soup.find_all('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
- github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
+ github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.75)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn("skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title=title,
body=issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i, comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
a88d001e3925ab58820d5f5e167c27da9c3ab720
|
Style edits per PEP standards/style lint
|
diff --git a/migrateissues.py b/migrateissues.py
index 0dbea8b..2344c53 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,156 +1,159 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
+
class IssueComment(object):
def __init__(self, date, author, body):
- self.created_at = date
+ self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
- def body (self):
+ def body(self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
+
class Issue(object):
def __init__(self, issue_line):
- for k,v in issue_line.items():
+ for k, v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
- def get_body(self,node):
+ def get_body(self, node):
return node.find('pre').string
-
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
- self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
+ self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre'), self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
- author = self.get_user(node)
+ author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
- logging.info('got comments %s' % len(comments))
+ logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
+
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
+
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
- logging.warn( "skipping issue : %s" % (issue))
+ logging.warn("skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
- title = title,
- body = issue.body
+ title=title,
+ body=issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
- old_comments = github.issues.comments(options.github_project, git_issue.number)
- for i,comment in enumerate(issue.comments):
-
+ old_comments = github.issues.comments(options.github_project, git_issue.number)
+ for i, comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
- if bool(old_c.body) or old_c.body == comment.body :
+ if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
+
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
- raise
\ No newline at end of file
+ raise
|
arthur-debert/google-code-issues-migrator
|
4c1103548cb1174bdb2095d94e0cee275dafdc8c
|
PEPifying style
|
diff --git a/migrateissues.py b/migrateissues.py
index b97b913..0dbea8b 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,155 +1,156 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
+
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
- @property
+ @property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
-
+
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
- self.get_original_data()
+ self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
-
-
+
+
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
- self.comments = comments
+ self.comments = comments
logging.info('got comments %s' % len(comments))
@property
- def original_url(self):
+ def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
-
+
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
-
+
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
- content = get_url_content(url)
+ content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
- try:
+ try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
- logging.info('will post issue:%s' % issue)
+ logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
- git_issue = github.issues.open(options.github_project,
+ git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
- for old_c in old_comments:
+ for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
-
- return git_issue
-
+
+ return git_issue
+
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
-
+
if __name__ == "__main__":
- import optparse
- import sys
+ import optparse
+ import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
- try:
+ try:
issues_data = download_issues()
process_issues(issues_data)
except:
- parser.print_help()
+ parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
213b48612ec08d96784aae652564bac247d3479f
|
Fix typo.
|
diff --git a/migrateissues.py b/migrateissues.py
index b97b913..c607210 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,155 +1,155 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
- parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
+ parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Your Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
6a43efdb99b510d70e30a91ce5b8852a10d36171
|
Just include summary as part of title for new github issue.
|
diff --git a/migrateissues.py b/migrateissues.py
index ac515e1..6b09097 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,200 +1,200 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
g_statusre = \
'^(' + \
'Issue has not had initial review yet' + '|' + \
'Problem reproduced \/ Need acknowledged' + '|' + \
'Work on this issue has begun' + '|' + \
'Waiting on feedback or additional information' + '|' + \
'Developer made source code changes, QA should verify' + '|' + \
'QA has verified that the fix worked' + '|' + \
'This was not a valid issue report' + '|' + \
'Unable to reproduce the issue' + '|' + \
'This report duplicates an existing issue' + '|' + \
'We decided to not take action on this issue' + '|' + \
'The requested non-coding task was completed' + \
')$'
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
comment = unicode(node.find('pre').renderContents(), 'utf-8', 'replace')
return comment
def get_labels(self, soup):
self.labels = []
self.milestones = [] # Milestones are a form of label in googlecode
for node in soup.findAll(attrs = { 'class' : 'label' }):
label = unicode(re.sub('<\/?b>', '', node.renderContents()))
if re.match('^Milestone-', label):
self.milestones.append(re.sub('^Milestone-', '', label))
else:
self.labels.append(label)
return
def get_status(self, soup):
node = soup.find(name = 'span', attrs = { 'title' : re.compile(g_statusre) })
self.status = unicode(node.string)
self.labels.append("Status-%s" % self.status)
return
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
descriptionstring = unicode(descriptionnode.find('pre').renderContents(), 'utf-8', 'replace')
self.body = unicode("%s<br />Original link: %s" % (descriptionstring , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
if not re.match('^\\n<i>\(No comment was entered for this change\.\)<\/i>\\n$', body):
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
self.get_labels(soup)
logging.info('got labels %s' % len(self.labels))
logging.info('got milestones %s' % len(self.milestones))
self.get_status(soup)
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified worksforme duplicate done".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
- title = "%s - %s " % (issue.id, issue.summary)
+ title = "%s" % issue.summary
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
7295d2d9911e69bb51163ec326e78e8a40c62e3d
|
Grab description and comments as UTF-8 and replace unrecognized characters. This fixes errors grabbing descriptions and comments when non-ascii characters are parsed.
|
diff --git a/migrateissues.py b/migrateissues.py
index 7740156..ac515e1 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,198 +1,200 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
g_statusre = \
'^(' + \
'Issue has not had initial review yet' + '|' + \
'Problem reproduced \/ Need acknowledged' + '|' + \
'Work on this issue has begun' + '|' + \
'Waiting on feedback or additional information' + '|' + \
'Developer made source code changes, QA should verify' + '|' + \
'QA has verified that the fix worked' + '|' + \
'This was not a valid issue report' + '|' + \
'Unable to reproduce the issue' + '|' + \
'This report duplicates an existing issue' + '|' + \
'We decided to not take action on this issue' + '|' + \
'The requested non-coding task was completed' + \
')$'
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
- return unicode(node.find('pre').renderContents())
+ comment = unicode(node.find('pre').renderContents(), 'utf-8', 'replace')
+ return comment
def get_labels(self, soup):
self.labels = []
self.milestones = [] # Milestones are a form of label in googlecode
for node in soup.findAll(attrs = { 'class' : 'label' }):
label = unicode(re.sub('<\/?b>', '', node.renderContents()))
if re.match('^Milestone-', label):
self.milestones.append(re.sub('^Milestone-', '', label))
else:
self.labels.append(label)
return
def get_status(self, soup):
node = soup.find(name = 'span', attrs = { 'title' : re.compile(g_statusre) })
self.status = unicode(node.string)
self.labels.append("Status-%s" % self.status)
return
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
- self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
+ descriptionstring = unicode(descriptionnode.find('pre').renderContents(), 'utf-8', 'replace')
+ self.body = unicode("%s<br />Original link: %s" % (descriptionstring , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
if not re.match('^\\n<i>\(No comment was entered for this change\.\)<\/i>\\n$', body):
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
self.get_labels(soup)
logging.info('got labels %s' % len(self.labels))
logging.info('got milestones %s' % len(self.milestones))
self.get_status(soup)
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified worksforme duplicate done".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
54c5f54f67f173827dc67ab3001f35f201984c7b
|
Add more statuses for closed issues to set github issue to closed.
|
diff --git a/migrateissues.py b/migrateissues.py
index c96bb1a..7740156 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,198 +1,198 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
g_statusre = \
'^(' + \
'Issue has not had initial review yet' + '|' + \
'Problem reproduced \/ Need acknowledged' + '|' + \
'Work on this issue has begun' + '|' + \
'Waiting on feedback or additional information' + '|' + \
'Developer made source code changes, QA should verify' + '|' + \
'QA has verified that the fix worked' + '|' + \
'This was not a valid issue report' + '|' + \
'Unable to reproduce the issue' + '|' + \
'This report duplicates an existing issue' + '|' + \
'We decided to not take action on this issue' + '|' + \
'The requested non-coding task was completed' + \
')$'
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
return unicode(node.find('pre').renderContents())
def get_labels(self, soup):
self.labels = []
self.milestones = [] # Milestones are a form of label in googlecode
for node in soup.findAll(attrs = { 'class' : 'label' }):
label = unicode(re.sub('<\/?b>', '', node.renderContents()))
if re.match('^Milestone-', label):
self.milestones.append(re.sub('^Milestone-', '', label))
else:
self.labels.append(label)
return
def get_status(self, soup):
node = soup.find(name = 'span', attrs = { 'title' : re.compile(g_statusre) })
self.status = unicode(node.string)
self.labels.append("Status-%s" % self.status)
return
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
if not re.match('^\\n<i>\(No comment was entered for this change\.\)<\/i>\\n$', body):
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
self.get_labels(soup)
logging.info('got labels %s' % len(self.labels))
logging.info('got milestones %s' % len(self.milestones))
self.get_status(soup)
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
- if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
+ if issue.status.lower() in "invalid closed fixed wontfix verified worksforme duplicate done".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
3315331d06ac8675d6f0efa34348894cb2714ca9
|
Add regex for checking statuses of open issues.
|
diff --git a/migrateissues.py b/migrateissues.py
index 1cc5373..c96bb1a 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,194 +1,198 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
g_statusre = \
'^(' + \
+ 'Issue has not had initial review yet' + '|' + \
+ 'Problem reproduced \/ Need acknowledged' + '|' + \
+ 'Work on this issue has begun' + '|' + \
+ 'Waiting on feedback or additional information' + '|' + \
'Developer made source code changes, QA should verify' + '|' + \
'QA has verified that the fix worked' + '|' + \
'This was not a valid issue report' + '|' + \
'Unable to reproduce the issue' + '|' + \
'This report duplicates an existing issue' + '|' + \
'We decided to not take action on this issue' + '|' + \
'The requested non-coding task was completed' + \
')$'
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
return unicode(node.find('pre').renderContents())
def get_labels(self, soup):
self.labels = []
self.milestones = [] # Milestones are a form of label in googlecode
for node in soup.findAll(attrs = { 'class' : 'label' }):
label = unicode(re.sub('<\/?b>', '', node.renderContents()))
if re.match('^Milestone-', label):
self.milestones.append(re.sub('^Milestone-', '', label))
else:
self.labels.append(label)
return
def get_status(self, soup):
node = soup.find(name = 'span', attrs = { 'title' : re.compile(g_statusre) })
self.status = unicode(node.string)
self.labels.append("Status-%s" % self.status)
return
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
if not re.match('^\\n<i>\(No comment was entered for this change\.\)<\/i>\\n$', body):
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
self.get_labels(soup)
logging.info('got labels %s' % len(self.labels))
logging.info('got milestones %s' % len(self.milestones))
self.get_status(soup)
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
3078c5868fea402140bd090af61adc3d5ff39128
|
Save labels as unicode strings.
|
diff --git a/migrateissues.py b/migrateissues.py
index 71144a5..1cc5373 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,194 +1,194 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
g_statusre = \
'^(' + \
'Developer made source code changes, QA should verify' + '|' + \
'QA has verified that the fix worked' + '|' + \
'This was not a valid issue report' + '|' + \
'Unable to reproduce the issue' + '|' + \
'This report duplicates an existing issue' + '|' + \
'We decided to not take action on this issue' + '|' + \
'The requested non-coding task was completed' + \
')$'
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
return unicode(node.find('pre').renderContents())
def get_labels(self, soup):
self.labels = []
self.milestones = [] # Milestones are a form of label in googlecode
for node in soup.findAll(attrs = { 'class' : 'label' }):
- label = re.sub('<\/?b>', '', node.renderContents())
+ label = unicode(re.sub('<\/?b>', '', node.renderContents()))
if re.match('^Milestone-', label):
self.milestones.append(re.sub('^Milestone-', '', label))
else:
self.labels.append(label)
return
def get_status(self, soup):
node = soup.find(name = 'span', attrs = { 'title' : re.compile(g_statusre) })
self.status = unicode(node.string)
self.labels.append("Status-%s" % self.status)
return
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
if not re.match('^\\n<i>\(No comment was entered for this change\.\)<\/i>\\n$', body):
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
self.get_labels(soup)
logging.info('got labels %s' % len(self.labels))
logging.info('got milestones %s' % len(self.milestones))
self.get_status(soup)
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
85eb2009d1020a5065f8a3eccac584e6ad029cbe
|
Get the status of an issue.
|
diff --git a/migrateissues.py b/migrateissues.py
index 52464f5..71144a5 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,176 +1,194 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
+g_statusre = \
+ '^(' + \
+ 'Developer made source code changes, QA should verify' + '|' + \
+ 'QA has verified that the fix worked' + '|' + \
+ 'This was not a valid issue report' + '|' + \
+ 'Unable to reproduce the issue' + '|' + \
+ 'This report duplicates an existing issue' + '|' + \
+ 'We decided to not take action on this issue' + '|' + \
+ 'The requested non-coding task was completed' + \
+ ')$'
+
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
return unicode(node.find('pre').renderContents())
def get_labels(self, soup):
self.labels = []
self.milestones = [] # Milestones are a form of label in googlecode
for node in soup.findAll(attrs = { 'class' : 'label' }):
label = re.sub('<\/?b>', '', node.renderContents())
if re.match('^Milestone-', label):
self.milestones.append(re.sub('^Milestone-', '', label))
else:
self.labels.append(label)
return
+
+ def get_status(self, soup):
+ node = soup.find(name = 'span', attrs = { 'title' : re.compile(g_statusre) })
+ self.status = unicode(node.string)
+ self.labels.append("Status-%s" % self.status)
+ return
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
if not re.match('^\\n<i>\(No comment was entered for this change\.\)<\/i>\\n$', body):
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
self.get_labels(soup)
logging.info('got labels %s' % len(self.labels))
logging.info('got milestones %s' % len(self.milestones))
+ self.get_status(soup)
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
14bd5a4c894b7df72adc167979ba685744283427
|
Ignore all comments that say '(No comment was entered for this change.)'.
|
diff --git a/migrateissues.py b/migrateissues.py
index b139e71..52464f5 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,175 +1,176 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
return unicode(node.find('pre').renderContents())
def get_labels(self, soup):
self.labels = []
self.milestones = [] # Milestones are a form of label in googlecode
for node in soup.findAll(attrs = { 'class' : 'label' }):
label = re.sub('<\/?b>', '', node.renderContents())
if re.match('^Milestone-', label):
self.milestones.append(re.sub('^Milestone-', '', label))
else:
self.labels.append(label)
return
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
- comments.append(IssueComment(date, author, body))
+ if not re.match('^\\n<i>\(No comment was entered for this change\.\)<\/i>\\n$', body):
+ comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
self.get_labels(soup)
logging.info('got labels %s' % len(self.labels))
logging.info('got milestones %s' % len(self.milestones))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
0572df37bcaf157ec821ae9fc2dc0ecc8d08019f
|
Extract milestones as well as labels.
|
diff --git a/migrateissues.py b/migrateissues.py
index e853ed2..b139e71 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,169 +1,175 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
return unicode(node.find('pre').renderContents())
def get_labels(self, soup):
- labels = []
+ self.labels = []
+ self.milestones = [] # Milestones are a form of label in googlecode
for node in soup.findAll(attrs = { 'class' : 'label' }):
- labels.append(re.sub('<\/?b>', '', node.renderContents()))
- return labels
+ label = re.sub('<\/?b>', '', node.renderContents())
+ if re.match('^Milestone-', label):
+ self.milestones.append(re.sub('^Milestone-', '', label))
+ else:
+ self.labels.append(label)
+ return
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
- self.labels = self.get_labels(soup)
+ self.get_labels(soup)
logging.info('got labels %s' % len(self.labels))
+ logging.info('got milestones %s' % len(self.milestones))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
c9fede501e2d3823aa12d25e8d3c898dae016cca
|
Get labels from issues.
|
diff --git a/migrateissues.py b/migrateissues.py
index dd6e531..e853ed2 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,161 +1,169 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
return unicode(node.find('pre').renderContents())
+
+ def get_labels(self, soup):
+ labels = []
+ for node in soup.findAll(attrs = { 'class' : 'label' }):
+ labels.append(re.sub('<\/?b>', '', node.renderContents()))
+ return labels
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
+ self.labels = self.get_labels(soup)
+ logging.info('got labels %s' % len(self.labels))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
223d645f5c8d6f342927ac2c5e6f714401799cdb
|
Render contents of description and comments. Prevents empty comments and keeps certain elements, like links.
|
diff --git a/migrateissues.py b/migrateissues.py
index 8117ede..dd6e531 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,161 +1,161 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
- return node.find('pre').string
+ return unicode(node.find('pre').renderContents())
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
- self.body = "%s</br>Original link: %s" % (descriptionnode.find('pre') , self.original_url)
+ self.body = unicode("%s<br />Original link: %s" % (descriptionnode.find('pre').renderContents() , self.original_url))
datenode = descriptionnode.find(attrs={'class' : 'date'})
datestring = datenode['title']
try:
self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
56202d75111635ee64ff734c349a767343b02f9c
|
Use more accurate time for description and comments.
|
diff --git a/migrateissues.py b/migrateissues.py
index b561c7c..8117ede 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,161 +1,161 @@
import csv
import logging
import datetime
import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
datenode = node.find(attrs={'class' : 'date'})
- datestring = datenode.string
+ datestring = datenode['title']
try:
- return datetime.datetime.strptime(datestring, '%b %d, %Y')
+ return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
authornode = node.find(attrs={'class' : 'author'})
userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
return userhrefnode.string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
self.body = "%s</br>Original link: %s" % (descriptionnode.find('pre') , self.original_url)
datenode = descriptionnode.find(attrs={'class' : 'date'})
- datestring = datenode.string
+ datestring = datenode['title']
try:
- self.created_at = datetime.datetime.strptime(datestring, '%b %d, %Y')
+ self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
9572dd1f37d78993cace80b83efb504f92427c19
|
Fine tune queries to nodes from parser.
|
diff --git a/migrateissues.py b/migrateissues.py
index b97b913..b561c7c 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,155 +1,161 @@
import csv
import logging
import datetime
+import re
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
- created_at_raw = node.find('span', 'date').string
+ datenode = node.find(attrs={'class' : 'date'})
+ datestring = datenode.string
try:
- return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
+ return datetime.datetime.strptime(datestring, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
- return node.findAll('a')[1].string
+ authornode = node.find(attrs={'class' : 'author'})
+ userhrefnode = authornode.find(attrs={'href' : re.compile('^\/u\/')})
+ return userhrefnode.string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
- self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
- created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
+ descriptionnode = soup.find(attrs={'class' : "cursor_off vt issuedescription"})
+ self.body = "%s</br>Original link: %s" % (descriptionnode.find('pre') , self.original_url)
+ datenode = descriptionnode.find(attrs={'class' : 'date'})
+ datestring = datenode.string
try:
- self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
+ self.created_at = datetime.datetime.strptime(datestring, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
- for node in soup.findAll('td', "vt issuecomment"):
+ for node in soup.findAll(attrs={'class' : "cursor_off vt issuecomment"}):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
b2557be6311ef24eedf43c1402317bb6271d594c
|
use the gdata issues api, migrate labels, revamp command line options
|
diff --git a/migrate-issues b/migrate-issues
index 5ac07cf..d5dae6b 100755
--- a/migrate-issues
+++ b/migrate-issues
@@ -1,154 +1,118 @@
#!/usr/bin/env python
-import csv
+import optparse
+import sys
+import re
import logging
import datetime
-from StringIO import StringIO
+import dateutil.parser
-import httplib2
from github2.client import Github
-from BeautifulSoup import BeautifulSoup
-
-options = None
-
-logging.basicConfig(level=logging.INFO)
-
-def get_url_content(url):
- h = httplib2.Http(".cache")
- resp, content = h.request(url, "GET")
- return content
-
-class IssueComment(object):
- def __init__(self, date, author, body):
- self.created_at = date
- self.body_raw = body
- self.author = author
- self.user = options.github_user_name
-
- @property
- def body (self):
- return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
-
- def __repr__(self):
- return self.body.encode('utf-8')
-
-class Issue(object):
-
- def __init__(self, issue_line):
- for k,v in issue_line.items():
- setattr(self, k.lower(), v)
- logging.info("Issue #%s: %s" % (self.id, self.summary))
- self.get_original_data()
-
- def parse_date(self, node):
- created_at_raw = node.find('span', 'date').string
- try:
- return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
- except ValueError: # if can't parse time, just assume now
- return datetime.datetime.now
-
- def get_user(self, node):
- return node.findAll('a')[1].string
-
- def get_body(self,node):
- return node.find('pre').string
-
- def get_original_data(self):
- logging.info("GET %s" % self.original_url)
- content = get_url_content(self.original_url)
- soup = BeautifulSoup(content)
- self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
- created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
- try:
- self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
- except ValueError: # if can't parse time, just assume now
- self.created_at = datetime.datetime.now
- comments = []
- for node in soup.findAll('div', "vt issuecomment"):
- try:
- date = self.parse_date(node)
- author = self.get_user(node)
- body = self.get_body(node)
- comments.append(IssueComment(date, author, body))
- except:
- pass
- self.comments = comments
- logging.info('got comments %s' % len(comments))
-
- @property
- def original_url(self):
- gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
- return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
-
- def __repr__(self):
- return u"%s - %s " % (self.id, self.summary)
-
-def download_issues():
- url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
- logging.info('Downloading %s' % url)
- content = get_url_content(url)
- f = StringIO(content)
- return f
-
-def post_to_github(issue, sync_comments=True):
- logging.info('should post %s', issue)
- github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.5)
- if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
- issue.status = 'closed'
- else:
- issue.status = 'open'
- try:
- git_issue = github.issues.show(options.github_project, int(issue.id))
- logging.warn( "skipping issue : %s" % (issue))
- except RuntimeError:
- title = "%s" % (issue.summary)
- logging.info('will post issue:%s' % issue)
- logging.info("issue did not exist")
- git_issue = github.issues.open(options.github_project,
- title = title,
- body = issue.body
- )
- if issue.status == 'closed':
- github.issues.close(options.github_project, git_issue.number)
- if sync_comments is False:
- return git_issue
- old_comments = github.issues.comments(options.github_project, git_issue.number)
- for i,comment in enumerate(issue.comments):
- exists = False
- for old_c in old_comments:
- # issue status changes have empty bodies in google code , exclude those:
- if bool(old_c.body) or old_c.body == comment.body:
- exists = True
- logging.info("Found comment there, skipping")
- break
- if not exists:
- #logging.info('posting comment %s', comment.body.encode('utf-8'))
- try:
- github.issues.comment(options.github_project, git_issue.number, comment)
- except:
- logging.exception("Failed to post comment %s for issue %s" % (i, issue))
-
- return git_issue
-
-def process_issues(issues_csv, sync_comments=True):
- reader = csv.DictReader(issues_csv)
- issues = [Issue(issue_line) for issue_line in reader]
- [post_to_github(i, sync_comments) for i in issues]
+
+import gdata.projecthosting.client
+import gdata.projecthosting.data
+import gdata.gauth
+import gdata.client
+import gdata.data
+import atom.http_core
+import atom.core
+
+GITHUB_REQUESTS_PER_SECOND = 0.5
+GOOGLE_MAX_RESULTS = 25
+
+logging.basicConfig(level=logging.ERROR)
+
+def output(string):
+ sys.stdout.write(string)
+ sys.stdout.flush()
+
+def add_issue_to_github(issue):
+ id = re.search('\d+$', issue.id.text).group(0)
+ title = issue.title.text
+ link = issue.link[1].href
+ content = issue.content.text
+ body = '<pre>%s</pre><br>Original link: %s' % (content, link)
+
+ output('Adding issue %s' % (id))
+
+ github_issue = None
+
+ if options.dry_run is not True:
+ github_issue = github.issues.open(github_project, title=title, body=body.encode('utf-8'))
+ github.issues.add_label(github_project, github_issue.number, "imported")
+
+ if issue.status.text.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
+ if options.dry_run is not True:
+ github.issues.close(github_project, github_issue.number)
+
+ # Add any labels
+ if len(issue.label) > 0:
+ output(', adding labels')
+ for label in issue.label:
+ if options.dry_run is not True:
+ github.issues.add_label(github_project, github_issue.number, label.text.encode('utf-8'))
+ output('.')
+
+ # Add any comments
+ start_index = 1
+ max_results = GOOGLE_MAX_RESULTS
+ while True:
+ comments_feed = google.get_comments(google_project_name, id, query=gdata.projecthosting.client.Query(start_index=start_index, max_results=max_results))
+ if len(comments_feed.entry) is 0:
+ break;
+ if start_index is 1:
+ output(', adding comments')
+ for comment in comments_feed.entry:
+ add_comment_to_github(comment, github_issue)
+ output('.')
+ start_index += max_results
+ output('\n')
+
+def add_comment_to_github(comment, github_issue):
+ id = re.search('\d+$', comment.id.text).group(0)
+ link = comment.link[0].href
+ author = comment.author[0].name.text
+ date = dateutil.parser.parse(comment.published.text).strftime('%B %d, %Y %H:%M:%S')
+ content = comment.content.text
+ body = '%s on %s:<br><pre>%s</pre><br>Original link: %s'% (author, date, content, link)
+
+ logging.info('Adding comment %s', id)
+
+ if options.dry_run is not True:
+ github.issues.comment(github_project, github_issue.number, body.encode('utf-8'))
+
+def process_issues():
+ start_index = 1
+ max_results = GOOGLE_MAX_RESULTS
+ while True:
+ issues_feed = google.get_issues(google_project_name, query=gdata.projecthosting.client.Query(start_index=start_index, max_results=max_results))
+ if len(issues_feed.entry) is 0:
+ break;
+ for issue in issues_feed.entry:
+ add_issue_to_github(issue)
+ start_index += max_results
if __name__ == "__main__":
- import optparse
- import sys
- usage = "usage: %prog [options]"
- parser = optparse.OptionParser(usage)
- parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
- parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
- parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
- parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
- options, args = parser.parse_args(args=sys.argv, values=None)
+ usage = "usage: %prog [options] <google_project_name> <github_api_token> <github_user_name> <github_project>"
+ description = "Migrate all issues from a Google Code project to a Github project."
+ parser = optparse.OptionParser(usage=usage, description=description)
+ parser.add_option('-d', '--dry-run', action="store_true", dest="dry_run", help="Don't modify anything on Github")
+ options, args = parser.parse_args()
+
+ if len(args) != 4:
+ parser.error('incorrect number of arguments')
+
+ google_project_name = args[0]
+ github_api_token = args[1]
+ github_user_name = args[2]
+ github_project = args[3]
+
+ google = gdata.projecthosting.client.ProjectHostingClient()
+ github = Github(username=github_user_name, api_token=github_api_token, requests_per_second=GITHUB_REQUESTS_PER_SECOND)
+
try:
- issues_data = download_issues()
- process_issues(issues_data)
+ process_issues()
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
5970351335f7f468dca18cb0584b160ce2bbd933
|
whitespace cleanup
|
diff --git a/migrate-issues b/migrate-issues
index 795b3fa..5ac07cf 100755
--- a/migrate-issues
+++ b/migrate-issues
@@ -1,156 +1,154 @@
-#! /usr/bin/env python
+#!/usr/bin/env python
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.INFO)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
- @property
+ @property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
- self.get_original_data()
+ self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
-
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('div', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
- self.comments = comments
+ self.comments = comments
logging.info('got comments %s' % len(comments))
@property
- def original_url(self):
+ def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
-
+
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
- content = get_url_content(url)
+ content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.5)
if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
issue.status = 'closed'
else:
issue.status = 'open'
- try:
+ try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s" % (issue.summary)
- logging.info('will post issue:%s' % issue)
+ logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
- git_issue = github.issues.open(options.github_project,
+ git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
-
exists = False
- for old_c in old_comments:
+ for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
- if bool(old_c.body) or old_c.body == comment.body :
+ if bool(old_c.body) or old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
- return git_issue
-
+ return git_issue
+
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
-
+
if __name__ == "__main__":
- import optparse
- import sys
+ import optparse
+ import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
options, args = parser.parse_args(args=sys.argv, values=None)
- try:
+ try:
issues_data = download_issues()
process_issues(issues_data)
except:
- parser.print_help()
+ parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
09ec21c009c9a9bf7c6f491ff6f5e0bbc015a195
|
make the script executable
|
diff --git a/migrateissues.py b/migrateissues.py
old mode 100644
new mode 100755
index 9f19a38..795b3fa
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,154 +1,156 @@
+#! /usr/bin/env python
+
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.INFO)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('div', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.5)
if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s" % (issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
49c391e30d6677dddbc87890952f0186452e84b4
|
google code issue comments are contained in divs now
|
diff --git a/migrateissues.py b/migrateissues.py
index 6da7a11..9f19a38 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,154 +1,154 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.INFO)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
- for node in soup.findAll('td', "vt issuecomment"):
+ for node in soup.findAll('div', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.5)
if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s" % (issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
20214ea41c5be2ae0ef86abb9e2f291ea98d66e0
|
set default logging level to INFO
|
diff --git a/migrateissues.py b/migrateissues.py
index 48743dc..6da7a11 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,154 +1,154 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
-logging.basicConfig(level=logging.DEBUG)
+logging.basicConfig(level=logging.INFO)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.5)
if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s" % (issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
14713e0ed21f4c6dc32c30aeca21cad8a4c58eb3
|
slow down api requests to one every two seconds
|
diff --git a/migrateissues.py b/migrateissues.py
index db5b058..48743dc 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,154 +1,154 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
- github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.8)
+ github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.5)
if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s" % (issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
8a0c52cafbad441829f2b0ff9241506c197483d2
|
no need to declare options a global as we're not in a function
|
diff --git a/migrateissues.py b/migrateissues.py
index 28a7d22..db5b058 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,155 +1,154 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.8)
if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s" % (issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
- global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
306500dbd0fb29444dbc26b8a20150eb44056ace
|
don't tack the google issue id onto the github issue title, get rid of trailing space
|
diff --git a/migrateissues.py b/migrateissues.py
index 2e3f5fd..28a7d22 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,155 +1,155 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.8)
if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
- title = "%s - %s " % (issue.id, issue.summary)
+ title = "%s" % (issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
c019d9baf1419e156d6d4e2c9f6d9709a7a2bbf9
|
treat 'Done' and 'Duplicate' statuses as closed
|
diff --git a/migrateissues.py b/migrateissues.py
index 5f932dc..2e3f5fd 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,155 +1,155 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.8)
- if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
+ if issue.status.lower() in "invalid closed fixed wontfix verified done duplicate".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
c9e4da781fec586c0d5f01d4a737682856b59717
|
make sure we stay under the one request per second cap
|
diff --git a/migrateissues.py b/migrateissues.py
index c2f988b..5f932dc 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,155 +1,155 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
- github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
+ github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=0.8)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
|
arthur-debert/google-code-issues-migrator
|
8727855689db38eac59ca123b59002cfe6c43365
|
add ending newline
|
diff --git a/migrateissues.py b/migrateissues.py
index b97b913..c2f988b 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,155 +1,155 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
try:
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
try:
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
except ValueError: # if can't parse time, just assume now
self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
- raise
\ No newline at end of file
+ raise
|
arthur-debert/google-code-issues-migrator
|
7d50f94f7acfdffa90f697a33ab98af0a662534f
|
Fixed issues
|
diff --git a/migrateissues.py b/migrateissues.py
index b98bf5a..b97b913 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,146 +1,155 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
+ logging.info("Issue #%s: %s" % (self.id, self.summary))
self.get_original_data()
def parse_date(self, node):
- created_at_raw = node.find('span', 'date').string
- return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
+ created_at_raw = node.find('span', 'date').string
+ try:
+ return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
+ except ValueError: # if can't parse time, just assume now
+ return datetime.datetime.now
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
+ logging.info("GET %s" % self.original_url)
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
- self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
+ try:
+ self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
+ except ValueError: # if can't parse time, just assume now
+ self.created_at = datetime.datetime.now
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
+ logging.info('Downloading %s' % url)
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
# issue status changes have empty bodies in google code , exclude those:
if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
77809a13ad992c031e11b18f2641f124d60fd91d
|
Fixed import of comments with empty bodies ( as in google code issue status changes).
|
diff --git a/migrateissues.py b/migrateissues.py
index fd9acd7..b98bf5a 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,145 +1,146 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
- for old_c in old_comments:
- if old_c.body == comment.body:
+ for old_c in old_comments:
+ # issue status changes have empty bodies in google code , exclude those:
+ if bool(old_c.body) or old_c.body == comment.body :
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
2a8b5ba86835ae2566a8af2aec11dbd404595775
|
made documentation more explanatory
|
diff --git a/migrateissues.py b/migrateissues.py
index 7a97f94..fd9acd7 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,145 +1,145 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
if old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
- parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name")
+ parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name:: user-name/project-name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
63c534f015629a9f792849240ea13e950715acbb
|
Improved usage message
|
diff --git a/README.mkd b/README.mkd
index 2372e95..4a033aa 100644
--- a/README.mkd
+++ b/README.mkd
@@ -1,11 +1,22 @@
This is a simple script to move issues from google code to github.
Some liberties have been taken (as we cannot, for example, know which google user corresponds to other user on github). But most information is complete.
Requirements:
* (httplib2)[http://code.google.com/p/httplib2/]
* (python github)[http://github.com/ask/python-github2]
Usage:
- ./migrateissues.py --google-project-name=[name] --github-api-token=[token] --github-username=[git username] --github-project=[github project name]
\ No newline at end of file
+ migrateissues.py [options]
+
+ Options:
+ -h, --help show this help message and exit
+ -g GOOGLE_PROJECT_NAME, --google-project-name=GOOGLE_PROJECT_NAME
+ The project name (from the URL) from google code.
+ -t GITHUB_API_TOKEN, --github-api-token=GITHUB_API_TOKEN
+ Yout Github api token
+ -u GITHUB_USER_NAME, --github-user-name=GITHUB_USER_NAME
+ The Github username
+ -p GITHUB_PROJECT, --github-project=GITHUB_PROJECT
+ The Github project name
diff --git a/migrateissues.py b/migrateissues.py
index 2309241..7a97f94 100644
--- a/migrateissues.py
+++ b/migrateissues.py
@@ -1,145 +1,145 @@
import csv
import logging
import datetime
from StringIO import StringIO
import httplib2
from github2.client import Github
from BeautifulSoup import BeautifulSoup
options = None
logging.basicConfig(level=logging.DEBUG)
def get_url_content(url):
h = httplib2.Http(".cache")
resp, content = h.request(url, "GET")
return content
class IssueComment(object):
def __init__(self, date, author, body):
self.created_at = date
self.body_raw = body
self.author = author
self.user = options.github_user_name
@property
def body (self):
return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
def __repr__(self):
return self.body.encode('utf-8')
class Issue(object):
def __init__(self, issue_line):
for k,v in issue_line.items():
setattr(self, k.lower(), v)
self.get_original_data()
def parse_date(self, node):
created_at_raw = node.find('span', 'date').string
return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
def get_user(self, node):
return node.findAll('a')[1].string
def get_body(self,node):
return node.find('pre').string
def get_original_data(self):
content = get_url_content(self.original_url)
soup = BeautifulSoup(content)
self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
comments = []
for node in soup.findAll('td', "vt issuecomment"):
try:
date = self.parse_date(node)
author = self.get_user(node)
body = self.get_body(node)
comments.append(IssueComment(date, author, body))
except:
pass
self.comments = comments
logging.info('got comments %s' % len(comments))
@property
def original_url(self):
gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
def __repr__(self):
return u"%s - %s " % (self.id, self.summary)
def download_issues():
url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
content = get_url_content(url)
f = StringIO(content)
return f
def post_to_github(issue, sync_comments=True):
logging.info('should post %s', issue)
github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
issue.status = 'closed'
else:
issue.status = 'open'
try:
git_issue = github.issues.show(options.github_project, int(issue.id))
logging.warn( "skipping issue : %s" % (issue))
except RuntimeError:
title = "%s - %s " % (issue.id, issue.summary)
logging.info('will post issue:%s' % issue)
logging.info("issue did not exist")
git_issue = github.issues.open(options.github_project,
title = title,
body = issue.body
)
if issue.status == 'closed':
github.issues.close(options.github_project, git_issue.number)
if sync_comments is False:
return git_issue
old_comments = github.issues.comments(options.github_project, git_issue.number)
for i,comment in enumerate(issue.comments):
exists = False
for old_c in old_comments:
if old_c.body == comment.body:
exists = True
logging.info("Found comment there, skipping")
break
if not exists:
#logging.info('posting comment %s', comment.body.encode('utf-8'))
try:
github.issues.comment(options.github_project, git_issue.number, comment)
except:
logging.exception("Failed to post comment %s for issue %s" % (i, issue))
return git_issue
def process_issues(issues_csv, sync_comments=True):
reader = csv.DictReader(issues_csv)
issues = [Issue(issue_line) for issue_line in reader]
[post_to_github(i, sync_comments) for i in issues]
if __name__ == "__main__":
import optparse
import sys
- usage = "usage: %prog [options] arg1 arg2"
+ usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name")
global options
options, args = parser.parse_args(args=sys.argv, values=None)
try:
issues_data = download_issues()
process_issues(issues_data)
except:
parser.print_help()
raise
\ No newline at end of file
|
arthur-debert/google-code-issues-migrator
|
df935bed0c8b13987efd444e9e19c124599b520a
|
initial checkin
|
diff --git a/README.mkd b/README.mkd
new file mode 100644
index 0000000..2372e95
--- /dev/null
+++ b/README.mkd
@@ -0,0 +1,11 @@
+This is a simple script to move issues from google code to github.
+
+Some liberties have been taken (as we cannot, for example, know which google user corresponds to other user on github). But most information is complete.
+
+Requirements:
+
+ * (httplib2)[http://code.google.com/p/httplib2/]
+ * (python github)[http://github.com/ask/python-github2]
+
+Usage:
+ ./migrateissues.py --google-project-name=[name] --github-api-token=[token] --github-username=[git username] --github-project=[github project name]
\ No newline at end of file
diff --git a/migrateissues.py b/migrateissues.py
new file mode 100644
index 0000000..2309241
--- /dev/null
+++ b/migrateissues.py
@@ -0,0 +1,145 @@
+import csv
+import logging
+import datetime
+from StringIO import StringIO
+
+import httplib2
+from github2.client import Github
+from BeautifulSoup import BeautifulSoup
+
+options = None
+
+logging.basicConfig(level=logging.DEBUG)
+
+def get_url_content(url):
+ h = httplib2.Http(".cache")
+ resp, content = h.request(url, "GET")
+ return content
+
+class IssueComment(object):
+ def __init__(self, date, author, body):
+ self.created_at = date
+ self.body_raw = body
+ self.author = author
+ self.user = options.github_user_name
+
+ @property
+ def body (self):
+ return ("%s - %s \n%s" % (self.author, self.created_at, self.body_raw)).encode('utf-8')
+
+ def __repr__(self):
+ return self.body.encode('utf-8')
+
+class Issue(object):
+
+ def __init__(self, issue_line):
+ for k,v in issue_line.items():
+ setattr(self, k.lower(), v)
+ self.get_original_data()
+
+ def parse_date(self, node):
+ created_at_raw = node.find('span', 'date').string
+ return datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
+
+ def get_user(self, node):
+ return node.findAll('a')[1].string
+
+ def get_body(self,node):
+ return node.find('pre').string
+
+
+ def get_original_data(self):
+ content = get_url_content(self.original_url)
+ soup = BeautifulSoup(content)
+ self.body = "%s</br>Original link: %s" % (soup.find('td', 'vt issuedescription').find('pre') , self.original_url)
+ created_at_raw = soup.find('td', 'vt issuedescription').find('span', 'date').string
+ self.created_at = datetime.datetime.strptime(created_at_raw, '%b %d, %Y')
+ comments = []
+ for node in soup.findAll('td', "vt issuecomment"):
+ try:
+ date = self.parse_date(node)
+ author = self.get_user(node)
+ body = self.get_body(node)
+ comments.append(IssueComment(date, author, body))
+ except:
+ pass
+ self.comments = comments
+ logging.info('got comments %s' % len(comments))
+
+ @property
+ def original_url(self):
+ gcode_base_url = "http://code.google.com/p/%s/" % options.google_project_name
+ return "%sissues/detail?id=%s" % (gcode_base_url, self.id)
+
+ def __repr__(self):
+ return u"%s - %s " % (self.id, self.summary)
+
+def download_issues():
+ url = "http://code.google.com/p/" + options.google_project_name + "/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary"
+ content = get_url_content(url)
+ f = StringIO(content)
+ return f
+
+def post_to_github(issue, sync_comments=True):
+ logging.info('should post %s', issue)
+ github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)
+ if issue.status.lower() in "invalid closed fixed wontfix verified".lower():
+ issue.status = 'closed'
+ else:
+ issue.status = 'open'
+ try:
+ git_issue = github.issues.show(options.github_project, int(issue.id))
+ logging.warn( "skipping issue : %s" % (issue))
+ except RuntimeError:
+ title = "%s - %s " % (issue.id, issue.summary)
+ logging.info('will post issue:%s' % issue)
+ logging.info("issue did not exist")
+ git_issue = github.issues.open(options.github_project,
+ title = title,
+ body = issue.body
+ )
+ if issue.status == 'closed':
+ github.issues.close(options.github_project, git_issue.number)
+ if sync_comments is False:
+ return git_issue
+ old_comments = github.issues.comments(options.github_project, git_issue.number)
+ for i,comment in enumerate(issue.comments):
+
+ exists = False
+ for old_c in old_comments:
+ if old_c.body == comment.body:
+ exists = True
+ logging.info("Found comment there, skipping")
+ break
+ if not exists:
+ #logging.info('posting comment %s', comment.body.encode('utf-8'))
+ try:
+ github.issues.comment(options.github_project, git_issue.number, comment)
+ except:
+ logging.exception("Failed to post comment %s for issue %s" % (i, issue))
+
+ return git_issue
+
+def process_issues(issues_csv, sync_comments=True):
+ reader = csv.DictReader(issues_csv)
+ issues = [Issue(issue_line) for issue_line in reader]
+ [post_to_github(i, sync_comments) for i in issues]
+
+
+if __name__ == "__main__":
+ import optparse
+ import sys
+ usage = "usage: %prog [options] arg1 arg2"
+ parser = optparse.OptionParser(usage)
+ parser.add_option('-g', '--google-project-name', action="store", dest="google_project_name", help="The project name (from the URL) from google code.")
+ parser.add_option('-t', '--github-api-token', action="store", dest="github_api_token", help="Yout Github api token")
+ parser.add_option('-u', '--github-user-name', action="store", dest="github_user_name", help="The Github username")
+ parser.add_option('-p', '--github-project', action="store", dest="github_project", help="The Github project name")
+ global options
+ options, args = parser.parse_args(args=sys.argv, values=None)
+ try:
+ issues_data = download_issues()
+ process_issues(issues_data)
+ except:
+ parser.print_help()
+ raise
\ No newline at end of file
|
clayton/phxrails-201006
|
81a0cc8dca30f0be510a4440b332f9644afc779c
|
More readable
|
diff --git a/code/after/rails/active.rb b/code/after/rails/active.rb
index 680999a..6091d16 100644
--- a/code/after/rails/active.rb
+++ b/code/after/rails/active.rb
@@ -1,14 +1,14 @@
# FLOG
# ----------------------
-# 9.0: flog total
-# 9.0: flog/method average
+# 15.1: flog total
+# 15.1: flog/method average
#
-# 9.0: main#active?
+# 15.1: main#active?
def active?
now = Time.now
- earliest = begin_date.strftime('%Y-%m-%d 06:00')
- latest = end_date.strftime('%Y-%m-%d 23:59')
+ earliest = begin_date.beginning_of_day + 6.hours
+ latest = end_date.end_of_day - 1.minute
now >= earliest && now <= latest
end
|
clayton/phxrails-201006
|
aec74b4e1797588aeba4267363a32daf5aa828da
|
PDF of presentation
|
diff --git a/docs/phxrails-201006.pdf b/docs/phxrails-201006.pdf
new file mode 100644
index 0000000..7b637d1
Binary files /dev/null and b/docs/phxrails-201006.pdf differ
|
clayton/phxrails-201006
|
7a64ff9d41049e8f88b67db129dff3c0bcd28a90
|
Finalized Keynote Presentation
|
diff --git a/docs/phxrails-201006.key b/docs/phxrails-201006.key
index bffe901..338af51 100644
Binary files a/docs/phxrails-201006.key and b/docs/phxrails-201006.key differ
|
clayton/phxrails-201006
|
7eb3ca676892a27d4f3dabbb1b1ce15bc0033944
|
Keynote Presentation
|
diff --git a/docs/phxrails-201006.key b/docs/phxrails-201006.key
new file mode 100644
index 0000000..bffe901
Binary files /dev/null and b/docs/phxrails-201006.key differ
|
clayton/phxrails-201006
|
d30d2167d79abb1fb4d5319f50e748f1ba09d7a2
|
Before and after of a fat rails controller
|
diff --git a/code/after/rails/statuses_controller.rb b/code/after/rails/statuses_controller.rb
new file mode 100644
index 0000000..4587f86
--- /dev/null
+++ b/code/after/rails/statuses_controller.rb
@@ -0,0 +1,40 @@
+# FLOG
+# -----------------
+# 16.1: flog total
+# 16.1: flog/method average
+#
+# 16.1: main#update
+
+# app/views/controllers/statuses_controller.rb
+def update
+ @status = current_account.statuses.find(params[:id])
+ if @status.update_attributes(params[:status])
+ flash[:notice] = 'Status was successfully updated.'
+ redirect_to(statuses_path)
+ else
+ render :action => "edit"
+ end
+end
+
+# app/views/models/status.rb
+
+after_update :adjust_account_statuses
+
+def adjust_account_statuses
+ statuses = account.statuses.reject{|s| s == self}
+
+ statuses.each do |status|
+ if status.position && (status.position >= position)
+ status.position = status.position + 1
+ status.save
+ end
+ end
+
+ statuses = current_account.statuses.all
+ previousStatusPosition = 0
+ statuses.each do |status|
+ status.position = previousStatusPosition + 1
+ status.save
+ previousStatusPosition = status.position
+ end
+end
\ No newline at end of file
diff --git a/code/before/rails/statuses_controller.rb b/code/before/rails/statuses_controller.rb
new file mode 100644
index 0000000..f8fcf1c
--- /dev/null
+++ b/code/before/rails/statuses_controller.rb
@@ -0,0 +1,38 @@
+# FLOG
+# -------------------------
+# 68.0: flog total
+# 68.0: flog/method average
+#
+# 68.0: main#update
+
+# PUT /statuses/1
+# PUT /statuses/1.xml
+def update
+ @status = current_account.statuses.find(params[:id])
+ respond_to do |format|
+ if @status.update_attributes(params[:status])
+ statuses = current_account.statuses.all
+ statuses.each do |status|
+ unless status.id == @status.id
+ if status.position && (status.position >= @status.position)
+ status.position = status.position + 1
+ status.save
+ end
+ end
+ end
+ statuses = current_account.statuses.all
+ previousStatusPosition = 0
+ statuses.each do |status|
+ status.position = previousStatusPosition + 1
+ status.save
+ previousStatusPosition = status.position
+ end
+ flash[:notice] = 'Status was successfully updated.'
+ format.html { redirect_to(statuses_path) }
+ format.xml { head :ok }
+ else
+ format.html { render :action => "edit" }
+ format.xml { render :xml => @status.errors, :status => :unprocessable_entity }
+ end
+ end
+end
|
clayton/phxrails-201006
|
c3ecc18a649a62134272758656a391a04f61a468
|
Even more view awesomness
|
diff --git a/code/after/rails/more_view_logic.rb b/code/after/rails/more_view_logic.rb
new file mode 100644
index 0000000..3e28376
--- /dev/null
+++ b/code/after/rails/more_view_logic.rb
@@ -0,0 +1,42 @@
+case org_type.name
+when 'A'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'A')) if !html.include?('A')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'A', :section_type => 'message')) if !html.include?('A')
+ end
+when 'B'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'B')) if !html.include?('B')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'B', :section_type => 'message')) if !html.include?('B')
+ end
+when 'C'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'C')) if !html.include?('C')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'C', :section_type => 'message')) if !html.include?('C')
+ end
+when 'D'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'D')) if !html.include?('D')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'D', :section_type => 'message')) if !html.include?('D')
+ end
+when 'E'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'E')) if !html.include?('E')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'E', :section_type => 'message')) if !html.include?('E')
+ end
+end
\ No newline at end of file
diff --git a/code/before/rails/more_view_logic.rb b/code/before/rails/more_view_logic.rb
new file mode 100644
index 0000000..3e28376
--- /dev/null
+++ b/code/before/rails/more_view_logic.rb
@@ -0,0 +1,42 @@
+case org_type.name
+when 'A'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'A')) if !html.include?('A')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'A', :section_type => 'message')) if !html.include?('A')
+ end
+when 'B'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'B')) if !html.include?('B')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'B', :section_type => 'message')) if !html.include?('B')
+ end
+when 'C'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'C')) if !html.include?('C')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'C', :section_type => 'message')) if !html.include?('C')
+ end
+when 'D'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'D')) if !html.include?('D')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'D', :section_type => 'message')) if !html.include?('D')
+ end
+when 'E'
+ if public_link == false
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ organization_newsletter_messages_url(organization, newsletter, :org_type => 'E')) if !html.include?('E')
+ else
+ html << sidebar_link(newsletter.get_messages_title(Organization.find(org_id[org_type.name])),
+ public_newsletter_messages_url(newsletter, :org_type => 'E', :section_type => 'message')) if !html.include?('E')
+ end
+end
\ No newline at end of file
|
clayton/phxrails-201006
|
ce2484196709ff8000ba92932518dbfa6d4642a9
|
Before and after rails view logic
|
diff --git a/code/after/rails/view_logic.rb b/code/after/rails/view_logic.rb
new file mode 100644
index 0000000..b44cbdb
--- /dev/null
+++ b/code/after/rails/view_logic.rb
@@ -0,0 +1,11 @@
+# app/views/products/index.html.erb
+display_remaining_items(@featured_product)
+
+# app/helpers/products_helper.rb
+def display_remaining_items(product)
+ return "" unless product.available?
+ remaining = pluralize(product.remaining, "item")
+ content_tag(:p, :class => "remaining") do
+ "#{remaining} left!"
+ end
+end
\ No newline at end of file
diff --git a/code/before/rails/view_logic.rb b/code/before/rails/view_logic.rb
new file mode 100644
index 0000000..a6298bd
--- /dev/null
+++ b/code/before/rails/view_logic.rb
@@ -0,0 +1,7 @@
+<% if @panel1_product.max_qty > 0 && @panel1_product.remaining < 20 && @panel1_product.available? %>
+ <% if @panel1_product.remaining == 1 %>
+ <p class="remaining"><%= @panel1_product.remaining %> item left!</p>
+ <% else %>
+ <p class="remaining"><%= @panel1_product.remaining %> items left!</p>
+ <% end %>
+<% end %>
\ No newline at end of file
|
clayton/phxrails-201006
|
41f5f9cd9dc8f36dbf5f45f51c17085c766e8e78
|
Before and After rails model method
|
diff --git a/code/after/rails/active.rb b/code/after/rails/active.rb
new file mode 100644
index 0000000..680999a
--- /dev/null
+++ b/code/after/rails/active.rb
@@ -0,0 +1,14 @@
+# FLOG
+# ----------------------
+# 9.0: flog total
+# 9.0: flog/method average
+#
+# 9.0: main#active?
+
+def active?
+ now = Time.now
+ earliest = begin_date.strftime('%Y-%m-%d 06:00')
+ latest = end_date.strftime('%Y-%m-%d 23:59')
+
+ now >= earliest && now <= latest
+end
diff --git a/code/before/rails/active.rb b/code/before/rails/active.rb
new file mode 100644
index 0000000..052f064
--- /dev/null
+++ b/code/before/rails/active.rb
@@ -0,0 +1,11 @@
+# FLOG
+# ------------------------------
+# 10.9: flog total
+# 10.9: flog/method average
+#
+# 10.9: main#active?
+
+def active?
+ today = Time.now.strftime('%Y-%m-%d %H:%M')
+ today >= self.begin_date.strftime('%Y-%m-%d 06:00') && today <= self.end_date.strftime('%Y-%m-%d 23:59')
+end
|
clayton/phxrails-201006
|
0c5d7d0d453e5b2cc9db99243600b26361be5909
|
Maybe we went too far
|
diff --git a/after/dog/dog.rb b/after/dog/dog.rb
index 5739e5b..48e1f5f 100644
--- a/after/dog/dog.rb
+++ b/after/dog/dog.rb
@@ -1,32 +1,32 @@
class Dog
attr_accessor :size, :bark, :guarding, :trained
def initialize(options)
self.size = options[:size]
self.bark = options[:bark]
self.guarding = options[:guarding]
self.trained = options[:trained]
end
# FLOG
# --------------------------
- # 20.3: flog total
- # 5.1: flog/method average
+ # 16.8: flog total
+ # 5.6: flog/method average
#
- # 7.0: Dog#bark_by_size
+ # 8.9: Dog#speak
# 6.8: Dog#initialize
-
def speak
return "#{@bark} #{@bark} #{@bark} #{@bark} #{@bark}" if guarding
return "" if trained
- bark_by_size
+ if @size == "Small"
+ @bark
+ elsif @size == "Medium"
+ "#{@bark} #{@bark}"
+ elsif @size == "Large"
+ "#{@bark} #{@bark} #{@bark}"
+ end
end
-private
- def bark_by_size
- volume = {"Small" => 1, "Medium" => 2, "Large" => 3}
- ([@bark] * volume[size]).join(" ")
- end
end
\ No newline at end of file
|
clayton/phxrails-201006
|
28d3f79a69e3ae7e378627e106d30c38640a540c
|
More Improvement?
|
diff --git a/after/dog/dog.rb b/after/dog/dog.rb
index 2e3ff1e..5739e5b 100644
--- a/after/dog/dog.rb
+++ b/after/dog/dog.rb
@@ -1,31 +1,32 @@
class Dog
attr_accessor :size, :bark, :guarding, :trained
def initialize(options)
self.size = options[:size]
self.bark = options[:bark]
self.guarding = options[:guarding]
self.trained = options[:trained]
end
# FLOG
# --------------------------
- # 16.8: flog total
- # 5.6: flog/method average
+ # 20.3: flog total
+ # 5.1: flog/method average
#
- # 8.9: Dog#speak
+ # 7.0: Dog#bark_by_size
# 6.8: Dog#initialize
+
def speak
return "#{@bark} #{@bark} #{@bark} #{@bark} #{@bark}" if guarding
return "" if trained
- if @size == "Small"
- @bark
- elsif @size == "Medium"
- "#{@bark} #{@bark}"
- elsif @size == "Large"
- "#{@bark} #{@bark} #{@bark}"
- end
+
+ bark_by_size
end
+private
+ def bark_by_size
+ volume = {"Small" => 1, "Medium" => 2, "Large" => 3}
+ ([@bark] * volume[size]).join(" ")
+ end
end
\ No newline at end of file
|
clayton/phxrails-201006
|
b0a2d29580e6aa074da0c9834662195875f6f447
|
Explicitly require the correct Dog class
|
diff --git a/before/dog/dog_spec.rb b/before/dog/dog_spec.rb
index c2f5f2c..d8ed5d8 100644
--- a/before/dog/dog_spec.rb
+++ b/before/dog/dog_spec.rb
@@ -1,35 +1,35 @@
-require File.join(File.dirname(File.expand_path(__FILE__)),"..", "..", "spec_helper.rb")
-require 'dog'
+require File.join(File.dirname(File.expand_path(__FILE__)),"..", "..", "spec_helper")
+require File.join(File.dirname(File.expand_path(__FILE__)),"dog")
describe "Dog" do
describe "speak" do
before(:each) do
@st_bernard = Dog.new({:size => "Large", :bark => "WOOF!"})
@hound = Dog.new({:size => "Medium", :bark => "Howwoooo!"})
@yorkie = Dog.new({:size => "Small", :bark => "yip!"})
@guarding = Dog.new({:size => "Large", :bark => "WUF!", :guarding => true})
@trained = Dog.new({:size => "Medium", :bark => "YapYap", :trained => true})
end
it "should bark a little if it's small" do
@yorkie.speak.should == "yip!"
end
it "should bark some more it's medium sizes" do
@hound.speak.should == "Howwoooo! Howwoooo!"
end
it "should bark a lot if it's big" do
@st_bernard.speak.should == "WOOF! WOOF! WOOF!"
end
it "should bark like crazy if it's a guard dog" do
@guarding.speak.should == "WUF! WUF! WUF! WUF! WUF!"
end
it "should not bark if it's a trained dog" do
@trained.speak.should == ""
end
end
end
\ No newline at end of file
|
clayton/phxrails-201006
|
82ed251ac3f413e4ee33c1351b885e9b918ee4b2
|
Improved Dog Class
|
diff --git a/after/dog/dog.rb b/after/dog/dog.rb
new file mode 100644
index 0000000..2e3ff1e
--- /dev/null
+++ b/after/dog/dog.rb
@@ -0,0 +1,31 @@
+class Dog
+ attr_accessor :size, :bark, :guarding, :trained
+
+ def initialize(options)
+ self.size = options[:size]
+ self.bark = options[:bark]
+ self.guarding = options[:guarding]
+ self.trained = options[:trained]
+ end
+
+ # FLOG
+ # --------------------------
+ # 16.8: flog total
+ # 5.6: flog/method average
+ #
+ # 8.9: Dog#speak
+ # 6.8: Dog#initialize
+
+ def speak
+ return "#{@bark} #{@bark} #{@bark} #{@bark} #{@bark}" if guarding
+ return "" if trained
+ if @size == "Small"
+ @bark
+ elsif @size == "Medium"
+ "#{@bark} #{@bark}"
+ elsif @size == "Large"
+ "#{@bark} #{@bark} #{@bark}"
+ end
+ end
+
+end
\ No newline at end of file
diff --git a/after/dog/dog_spec.rb b/after/dog/dog_spec.rb
new file mode 100644
index 0000000..d8ed5d8
--- /dev/null
+++ b/after/dog/dog_spec.rb
@@ -0,0 +1,35 @@
+require File.join(File.dirname(File.expand_path(__FILE__)),"..", "..", "spec_helper")
+require File.join(File.dirname(File.expand_path(__FILE__)),"dog")
+
+describe "Dog" do
+ describe "speak" do
+ before(:each) do
+ @st_bernard = Dog.new({:size => "Large", :bark => "WOOF!"})
+ @hound = Dog.new({:size => "Medium", :bark => "Howwoooo!"})
+ @yorkie = Dog.new({:size => "Small", :bark => "yip!"})
+ @guarding = Dog.new({:size => "Large", :bark => "WUF!", :guarding => true})
+ @trained = Dog.new({:size => "Medium", :bark => "YapYap", :trained => true})
+ end
+
+ it "should bark a little if it's small" do
+ @yorkie.speak.should == "yip!"
+ end
+
+ it "should bark some more it's medium sizes" do
+ @hound.speak.should == "Howwoooo! Howwoooo!"
+ end
+
+ it "should bark a lot if it's big" do
+ @st_bernard.speak.should == "WOOF! WOOF! WOOF!"
+ end
+
+ it "should bark like crazy if it's a guard dog" do
+ @guarding.speak.should == "WUF! WUF! WUF! WUF! WUF!"
+ end
+
+ it "should not bark if it's a trained dog" do
+ @trained.speak.should == ""
+ end
+
+ end
+end
\ No newline at end of file
|
clayton/phxrails-201006
|
d53259f722ade2cafe4933fde8999ee8a063e9f5
|
Before: Dog class
|
diff --git a/before/dog/dog.rb b/before/dog/dog.rb
new file mode 100644
index 0000000..93c8c5c
--- /dev/null
+++ b/before/dog/dog.rb
@@ -0,0 +1,45 @@
+class Dog
+ attr_accessor :size, :bark, :guarding, :trained
+
+ def initialize(options)
+ self.size = options[:size]
+ self.bark = options[:bark]
+ self.guarding = options[:guarding]
+ self.trained = options[:trained]
+ end
+
+ # FLOG
+ # --------------------------
+ # 25.7: flog total
+ # 8.6: flog/method average
+ #
+ # 17.8: Dog#speak
+ def speak
+ if @size == "Small"
+ if guarding
+ "#{@bark} #{@bark} #{@bark} #{@bark} #{@bark}"
+ elsif trained
+ ""
+ else
+ @bark
+ end
+ elsif @size == "Medium"
+ if guarding
+ "#{@bark} #{@bark} #{@bark} #{@bark} #{@bark}"
+ elsif trained
+ ""
+ else
+ "#{@bark} #{@bark}"
+ end
+ elsif @size == "Large"
+ if guarding
+ "#{@bark} #{@bark} #{@bark} #{@bark} #{@bark}"
+ elsif trained
+ ""
+ else
+ "#{@bark} #{@bark} #{@bark}"
+ end
+ end
+ end
+
+end
\ No newline at end of file
diff --git a/before/dog/dog_spec.rb b/before/dog/dog_spec.rb
new file mode 100644
index 0000000..c2f5f2c
--- /dev/null
+++ b/before/dog/dog_spec.rb
@@ -0,0 +1,35 @@
+require File.join(File.dirname(File.expand_path(__FILE__)),"..", "..", "spec_helper.rb")
+require 'dog'
+
+describe "Dog" do
+ describe "speak" do
+ before(:each) do
+ @st_bernard = Dog.new({:size => "Large", :bark => "WOOF!"})
+ @hound = Dog.new({:size => "Medium", :bark => "Howwoooo!"})
+ @yorkie = Dog.new({:size => "Small", :bark => "yip!"})
+ @guarding = Dog.new({:size => "Large", :bark => "WUF!", :guarding => true})
+ @trained = Dog.new({:size => "Medium", :bark => "YapYap", :trained => true})
+ end
+
+ it "should bark a little if it's small" do
+ @yorkie.speak.should == "yip!"
+ end
+
+ it "should bark some more it's medium sizes" do
+ @hound.speak.should == "Howwoooo! Howwoooo!"
+ end
+
+ it "should bark a lot if it's big" do
+ @st_bernard.speak.should == "WOOF! WOOF! WOOF!"
+ end
+
+ it "should bark like crazy if it's a guard dog" do
+ @guarding.speak.should == "WUF! WUF! WUF! WUF! WUF!"
+ end
+
+ it "should not bark if it's a trained dog" do
+ @trained.speak.should == ""
+ end
+
+ end
+end
\ No newline at end of file
|
clayton/phxrails-201006
|
6cd80edb4d4726632caac5ecdb625111f8333e30
|
Spec Helper
|
diff --git a/spec_helper.rb b/spec_helper.rb
new file mode 100644
index 0000000..53ae29b
--- /dev/null
+++ b/spec_helper.rb
@@ -0,0 +1,2 @@
+require 'rubygems'
+require 'spec'
\ No newline at end of file
|
fberg/xmonad-config
|
f7089ab5dc54ba93e2f89b25068c2ca5a04c1840
|
added screenshot
|
diff --git a/screenshots/2010-09-27_21-58-30_2720x1024_scrot.png b/screenshots/2010-09-27_21-58-30_2720x1024_scrot.png
new file mode 100644
index 0000000..cb965ba
Binary files /dev/null and b/screenshots/2010-09-27_21-58-30_2720x1024_scrot.png differ
|
fberg/xmonad-config
|
66c7c25abbe9cecf5a79890dcb81f1a333eda2cd
|
fixed LICENSE and README
|
diff --git a/LICENSE b/LICENSE
index 94a9ed0..e147d42 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,674 +1,26 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
+Copyright 2010 Franz Berger. All rights reserved.
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
+Redistribution and use in source and binary forms, with or without modification, are
+permitted provided that the following conditions are met:
- Preamble
+ 1. Redistributions of source code must retain the above copyright notice, this list of
+ conditions and the following disclaimer.
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list
+ of conditions and the following disclaimer in the documentation and/or other materials
+ provided with the distribution.
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
+THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
+The views and conclusions contained in the software and documentation are those of the
+authors and should not be interpreted as representing official policies, either expressed
+or implied, of Franz Berger.
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- 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 General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- <program> Copyright (C) <year> <name of author>
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/README b/README
index e69de29..6863338 100644
--- a/README
+++ b/README
@@ -0,0 +1,38 @@
+Introduction
+----------------------------------
+This is my up-to-date xmonad configuration file (xmonad.hs).
+
+Installation
+----------------------------------
+Copy xmonad.hs to your $HOME/.xmonad directory; the icons directory goes some-
+where on your disk (I keep it at ~/.xmonad/icons).
+
+You'll probably want to adjust some settings in the top part of xmonad.hs,
+especially icon path and font/color settings. Also set your terminal emulator
+and favorite programs there.
+
+The 'oldstuff' directory contains older code snippets and color themes.
+
+Dependencies
+----------------------------------
+# xmonad & xmonad-contrib >= 0.9 (haven't tried pre-0.9 with the newest config)
+# dzen
+# dmenu (for dmenu_run; you can use another program launcher too, e.g.
+ XMonad.Prompt.Shell which is bound to M-S-p in this config)
+
+Notes
+----------------------------------
+Please note that my Haskell skills are pretty much non-existent and that this
+configuration file is more or less composed of stuff I've found at [1] or else-
+where on the web and adapted/personalized. The people who created these configs
+deserve the real credit. :P
+
+The icons are mostly from sm4tik's icon theme (see [2]) with the addition of a
+few self-made icons to indicate the current tiling algorithm.
+
+License
+----------------------------------
+See LICENSE file for details.
+
+[1] http://www.haskell.org/haskellwiki/Xmonad/Config_archive
+[2] http://dzen.geekmode.org/dwiki/doku.php?id=dzen:icon-packs
diff --git a/xmonad.hs b/xmonad.hs
index f87946d..c08e933 100644
--- a/xmonad.hs
+++ b/xmonad.hs
@@ -1,520 +1,520 @@
-- needed for custom GSConfig
{-# LANGUAGE NoMonomorphismRestriction #-}
import XMonad
import qualified XMonad.Actions.ConstrainedResize as ConstR
import XMonad.Actions.CopyWindow
import XMonad.Actions.CycleRecentWS
import XMonad.Actions.CycleWS
import XMonad.Actions.DynamicWorkspaces
import qualified XMonad.Actions.FlexibleResize as Flex
import XMonad.Actions.DwmPromote
import XMonad.Actions.GridSelect
import XMonad.Actions.MouseGestures
import XMonad.Actions.PhysicalScreens
import XMonad.Actions.WindowMenu
import XMonad.Hooks.DynamicLog hiding (shorten)
import XMonad.Hooks.DynamicLog (dzenColor)
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers (isDialog, isFullscreen)
import XMonad.Hooks.SetWMName
import XMonad.Hooks.UrgencyHook
import XMonad.Layout.Accordion
import XMonad.Layout.Gaps
import XMonad.Layout.Grid
import XMonad.Layout.IM
import XMonad.Layout.LayoutHints
import XMonad.Layout.LayoutModifier
import XMonad.Layout.Maximize
import XMonad.Layout.Minimize
import XMonad.Layout.Monitor
import XMonad.Layout.Named
import XMonad.Layout.NoBorders
import XMonad.Layout.PerWorkspace
import XMonad.Layout.Reflect
import XMonad.Layout.ResizableTile
import XMonad.Layout.Simplest
import XMonad.Layout.Spiral
import XMonad.Layout.SubLayouts
import XMonad.Layout.Tabbed
import XMonad.Layout.ThreeColumns
import XMonad.Layout.TwoPane
import XMonad.Layout.WindowNavigation
import XMonad.Prompt
import XMonad.Prompt.Shell
import XMonad.Prompt.XMonad
import XMonad.Util.EZConfig
import XMonad.Util.Run (spawnPipe)
import XMonad.Util.Scratchpad
import XMonad.Util.Themes
import qualified XMonad.StackSet as W
import Data.Ratio
import Data.List
import qualified Data.Map as M
import System.Exit
import System.IO (Handle)
import System.IO.UTF8
import System.Posix.Unistd
----------------------------------------------------------------------
-- Colors and Fonts
-- yettenet-style color theme
myGlobalBackground = "#000000"
myGlobalForeground = "#555555"
myLayoutColor = "#668800"
--myActiveColor = "#b88b10"
myActiveColor = "#807855"
--myActiveTextColor = "#262729"
myActiveTextColor = "#000000"
--myActiveBorderColor = "#b88b10"
myActiveBorderColor = myActiveColor
--myActiveBorderColor = "#807855"
myInactiveColor = "#262729"
myInactiveTextColor = "#807855"
myInactiveBorderColor = myInactiveColor
--myUrgentColor = "#ce5c00"
myUrgentColor = myGlobalBackground
--myUrgentTextColor = "#000000"
myUrgentTextColor = "#CE5C00"
myUrgentBorderColor = myUrgentTextColor
myTitleColor = "#FFFFFF"
myFontName = "-*-profont-*-*-*-*-11-*-*-*-*-*-*-*"
--myXftFontName = "xft:DejaVuSans Mono:size=7:bold"
myXftFontName = "xft:HandelGotDlig:size=8"
----------------------------------------------------------------------
-- Settings
myTerminal = "urxvtc"
myFileManager = "dolphin"
myScreenLock = "slock"
myScreenShot = "scrot '%F_%H-%M-%S_$wx$h_scrot.png' -e 'mv $f ~/screenshots/'"
myScreenShot2 = "sleep 0.2; " ++ myScreenShot ++ " -s" -- take shot of window or area
myBorderWidth = 1
myModMask = mod4Mask
myNumlockMask = mod2Mask
myWorkspaces = ["web", "math", "term", "fs", "comm", "code", "doc", "net", "misc"]
--myWorkspaces = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
--mySPRect = W.RationalRect 0.6 0.5 0.39 0.48 -- Rectangle in lower right corner
mySPRect = W.RationalRect 0.01 0.02 0.98 0.3 -- Quake-like terminal
myGSApps =
[ myTerminal ++ " -e vim ~/.xmonad/xmonad.hs"
, "mumble"
, "gwenview"
, "systemsettings"
, "firefox"
, "konqueror"
, "chromium-bin"
, "FBReader"
, "kile"
, "lyx"
, "gimp"
, "transmission"
, "tucan"
, "~/Mathematica/mathematica"
, "nitrogen ~/wallpapers"
]
myStatusXS = "1" -- Xinerama screen
-myIconPath = "/home/frank/.dzen2/icons/"
+myIconPath = "/home/frank/.xmonad/icons/"
myFocusFollowsMouse :: Bool
myFocusFollowsMouse = True
statusbarCmd =
"dzen2 " ++
"-bg '" ++ myGlobalBackground ++ "' " ++
"-fg '" ++ myGlobalForeground ++ "' " ++
-- "-w " ++ myStatusWidth ++ " " ++
"-sa " ++ "c " ++
"-fn '" ++ myFontName ++ "' " ++
"-xs " ++ myStatusXS ++ " " ++
"-ta " ++ "l " ++
"-e " ++ "onstart=lower"
launcherCmd =
"dmenu_run " ++
"-fn '" ++ myFontName ++ "' " ++
"-nb '" ++ myGlobalBackground ++ "' " ++
"-nf '" ++ myGlobalForeground ++ "' " ++
"-sb '" ++ myActiveColor ++ "' " ++
"-sf '" ++ myActiveTextColor ++ "' " ++
"-b " ++
"-i"
----------------------------------------------------------------------
-- Themes
-- Prompts
myPromptConfig :: XPConfig
myPromptConfig = defaultXPConfig
{ font = myFontName
-- , bgColor = "#111111"
, bgColor = myGlobalBackground
-- , fgColor = "#d5d3a7"
, fgColor = myGlobalForeground
, fgHLight = myActiveTextColor
, bgHLight = myActiveColor
-- , borderColor = "black"
-- , borderColor = myGlobalBackground
, promptBorderWidth = 0
, position = Bottom
, height = 13
, defaultText = []
-- temporary fix for http://code.google.com/p/xmonad/issues/detail?id=317
-- remove when upgrading to >xmonad-0.9.1
, promptKeymap = M.fromList [((controlMask,xK_c), quit)]
`M.union` promptKeymap defaultXPConfig
}
-- Decorations
myTheme :: Theme
myTheme = defaultTheme
{ activeColor = myActiveColor
, activeTextColor = myActiveTextColor
, activeBorderColor = myActiveBorderColor
, inactiveColor = myGlobalBackground
, inactiveTextColor = myInactiveTextColor
, inactiveBorderColor = myGlobalBackground
, urgentColor = myUrgentColor
, urgentTextColor = myUrgentTextColor
, urgentBorderColor = myUrgentBorderColor
, fontName = myFontName
, decoHeight = 13
-- , decoWidth = 300
}
-- GridSelect
myGSConfig = defaultGSConfig
{ gs_font = myXftFontName
}
----------------------------------------------------------------------
-- Keyboard and Mouse bindings
myKeys =
[ ("M-p" , spawn launcherCmd)
, ("M-S-p" , shellPrompt myPromptConfig)
, ("M-x" , xmonadPrompt myPromptConfig)
-- Close the focused Window (compatible with WindowCopy)
, ("M-S-c" , kill1)
-- Copy Window to all Workspaces
, ("M-S-a" , windows copyToAll)
-- Kill all the other copies (restore from previous keybinding)
, ("M-C-a" , killAllOtherCopies)
, ("M-/" , withFocused (sendMessage . maximizeRestore))
, ("M-y" , withFocused (\f -> sendMessage (MinimizeWin f)))
, ("M-S-y" , sendMessage RestoreNextMinimizedWin)
, ("M-<Return>" , dwmpromote)
, ("M-u" , focusUrgent)
, ("M-f" , spawn myFileManager)
, ("M-<Print>" , spawn myScreenShot)
, ("M-S-<Print>" , spawn myScreenShot2)
, ("M-S-\\" , spawn myScreenLock)
, ("M-s" , scratchpadSpawnActionTerminal myTerminal)
-- Reflect
-- , ((myModMask , xK_r) , sendMessage $ Toggle REFLECTX)
-- Resize
, ("M-i" , sendMessage Shrink)
, ("M-S-i" , sendMessage MirrorShrink)
, ("M-o" , sendMessage Expand)
, ("M-S-o" , sendMessage MirrorExpand)
-- GridSelect for windows
, ("M-g" , goToSelected myGSConfig)
, ("M-S-g" , bringSelected myGSConfig)
-- GridSelect for a nice application menu
, ("M-r" , spawnSelected myGSConfig myGSApps)
-- Move to next non-empty Workspace
, ("M-n" , moveTo Next EmptyWS)
-- Take the window with me
, ("M-S-n" , shiftTo Next EmptyWS)
-- Cycle through recent Workspaces with [Alt] + [Tab]
, ("M1-<Tab>" , cycleRecentWS [xK_Alt_L] xK_Tab xK_grave)
-- DynamicWorkspaces
, ("M-;" , selectWorkspace myPromptConfig)
, ("M-S-;" , withWorkspace myPromptConfig (windows . W.shift))
, ("M-<Backspace>" , renameWorkspace myPromptConfig)
, ("M-S-<Backspace>" , removeWorkspace)
]
++
-- GreedyView
[ ("M" ++ mask ++ ('-':key:[]) , windows $ f ws)
| (ws, key) <- zip myWorkspaces ['1'..]
, (f, mask) <- [(W.greedyView, "") , (W.shift, "-S"), (copy, "-C")]
]
++
-- XMonad.Actions.PhysicalScreens:
-- mod-{w,e}, Switch to physical/Xinerama screens 1 or 2
-- mod-shift-{w,e}, Move client to screen 1 or 2
[ ("M" ++ mask ++ ('-':key:[]) , f scr)
| (key, scr) <- zip "we" [0..]
, (f, mask) <- [ (viewScreen, "") , (sendToScreen, "-S") ]
]
++
-- WindowNavigator
[ ("M" ++ mask ++ ('-':key) , sendMessage $ f dir)
| (dir, key) <- zip [R, L, U, D, R, L, U, D] ["<Right>", "<Left>", "<Up>", "<Down>", "l", "h", "k", "j"]
, (f, mask) <- [ (Go, "") , (Swap, "-S") ]
]
++
-- SubLayouts
[ ("M-C" ++ ('-':key:[]) , sendMessage $ pullGroup dir)
| (dir, key) <- zip [L, R, U, D] "hjkl"
]
++
[ ("M-C-m" , withFocused (sendMessage . MergeAll))
, ("M-C-u" , withFocused (sendMessage . UnMerge))
, ("M-C-." , onGroup W.focusUp')
, ("M-C-," , onGroup W.focusDown')
]
myMouse = M.fromList $
[ ((myModMask , button3) , \w -> focus w >> Flex.mouseResizeWindow w)
, ((myModMask .|. shiftMask , button3) , \w -> focus w >> ConstR.mouseResizeWindow w True)
-- Maximize/Restore
, ((myModMask , button2) , \_ -> withFocused (sendMessage . maximizeRestore))
-- Mouse gestures
, ((myModMask .|. shiftMask , button1) , mouseGesture gestures)
]
where
gestures = M.fromList
[ ([] , focus)
, ([U] , \_ -> sendMessage (Swap U))
, ([D] , \_ -> sendMessage (Swap D))
, ([R] , \_ -> sendMessage (Swap R))
, ([L] , \_ -> sendMessage (Swap L))
--, ([D, U] , \_ -> sendMessage SwapWindow)
, ([R, D, L, U] , \_ -> sendMessage FirstLayout)
]
----------------------------------------------------------------------
-- Layouts
-- tabbedLayout = tabbed shrinkText defaultTheme
myLayoutHook =
avoidStruts $
-- smartBorders $
maximize $
minimize $
layoutHints $
configurableNavigation (noNavigateBorders) $
-- mkToggle (single REFLECTX) $ -- Tabbed layout (and others) crashes w/ Reflect :(
onWorkspaces [ "web", "fs" ]
( noBorders Full
||| tabbed
||| Mirror resizableTall
) $
-- onWorkspace "im"
-- ( layoutHints $ withIM (1/5) (ClassName "Pidgin" `And` Role "buddy_list") resizableTall
-- ) $
onWorkspace "doc"
( tabbed
||| resizableTall
||| Mirror resizableTall
||| noBorders Full
) $
-- generic Layout
genericLayout
where
genericLayout =
subLayout [] (Accordion ||| Simplest) $
( resizableTall
||| threeCol
||| Mirror resizableTall
||| tabbed
||| Grid
||| spiral (gRatio)
||| noBorders Full
)
resizableTall = ResizableTall nmaster delta ratio []
threeCol = ThreeCol nmaster delta ratio
tabbed = tabbedBottom shrinkText myTheme
nmaster = 1
delta = (3/100)
ratio = (1/2)
gRatio = toRational goldenRatio
goldenRatio = 2/(1+sqrt(5)::Double)
----------------------------------------------------------------------
-- Manage Hooks
myManageHook = composeAll . concat $
[ [ isDialog --> doFloat ]
, [ isFullscreen --> doFloat ]
, [ className =? c --> doShift t | (c, t) <- myClassNameWSShifts ]
, [ className =? c --> doFloat | c <- myClassNameFloats ]
, [ title =? t --> doFloat | t <- myTitleFloats ]
, [ resource =? r --> doFloat | r <- myResourceFloats ]
, [ fmap (t `isInfixOf`) title --> doFloat | t <- myMatchTitleAnywhereFloats ]
, [ fmap (c `isInfixOf`) className --> doFloat | c <- myMatchClassAnywhereFloats ]
]
where
myClassNameWSShifts =
[ ("Okular", "doc")
, ("Evince", "doc")
, ("trayer", "comm")
, ("stalonetray", "comm")
, ("XMathematica", "math")
, ("Transmission", "net")
, ("Firefox", "web")
--, ("Kmail", "mail")
--, ("Pidgin", "im")
]
myClassNameFloats =
[ "feh"
, "kget"
, "Gimp"
, "gimp"
, "MPlayer"
, "Smplayer"
, "Kio_uiserver"
, "Xmessage"
, "Kcalc"
, "Toplevel"
, "Nitrogen"
, "Dialog"
, "Gtk-chtheme"
, "VirtualBox"
, "Choqok"
, "Plasma-desktop"
, "Kruler"
, "Skype"
, "FBReader"
]
myTitleFloats =
[ "Downloads"
, "Iceweasel Preferences"
, "Save As..."
, "many more..."
, "Add-ons"
, "Progess Dialog"
, "Element Properties"
, "Xnest"
, "Authorization Dialog"
, "bashrun"
]
myResourceFloats =
[ "Dialog"
]
myMatchTitleAnywhereFloats =
[ "VLC"
, "Copying"
, "Moving"
, "Transferring"
, "Deleting"
, "Examining"
, "Gnuplot"
]
myMatchClassAnywhereFloats =
[ "Gkrellm"
, "Hz_"
, "Stylish"
]
----------------------------------------------------------------------
-- Status Bar and Logging w/ PrettyPrinter
myLogHook h = dynamicLogWithPP $ myPP h
myPP :: Handle -> PP
myPP h = defaultPP
-- dzenColor doesn't seem to work correcly anymore
-- { ppCurrent = dzenColor myActiveTextColor myActiveColor . wrap pad pad
{ ppCurrent = wrap ("^fg(" ++ myActiveColor ++ ")^r(4x13)^fg()") ("^fg(" ++ myActiveColor ++ ")^r(4x13)^fg()") . dzenColor myActiveTextColor myActiveColor
, ppSep = " "
, ppWsSep = ""
-- , ppVisible = dzenColor myInactiveTextColor myInactiveColor . wrap pad pad
, ppVisible = wrap ("^fg(" ++ myInactiveColor ++ ")^r(4x13)^fg()") ("^fg(" ++ myInactiveColor ++ ")^r(4x13)^fg()") . dzenColor myInactiveTextColor myInactiveColor
, ppLayout = dzenColor myLayoutColor "" . wrap "" "" .
(\x -> case replace x "Maximize Minimize Hinted " "" of
"Full" -> icon("full") ++ " Full"
"ResizableTall" -> icon("vertical_tiles") ++ " Tiled |"
"Mirror ResizableTall" -> icon("horizontal_tiles") ++ " Tiled -"
"ThreeCol" -> icon("threecol") ++ " ThreeCol"
"Tabbed Bottom Simplest" -> icon("tabbed") ++ " Tabbed"
"Spiral" -> icon("spiral") ++ " Spiral"
"Twopane" -> icon("twopane") ++ " TwoPane"
"Grid" -> icon("grid") ++ " Grid"
_ -> x
)
, ppTitle = dzenColor myTitleColor "" . wrap "" ""
--, ppHiddenNoWindows = dzenColor "" myInactiveColor . wrap pad pad
, ppHidden = wrap pad pad
, ppOutput = System.IO.UTF8.hPutStrLn h
, ppUrgent = dzenColor myUrgentTextColor myUrgentColor
--, ppUrgent = wrap ("^fg(" ++ myUrgentColor ++ ")^r(4x13)^fg()") ("^fg(" ++ myUrgentColor ++ ")^r(4x13)^fg()") . dzenColor myUrgentTextColor myUrgentColor
-- Filter out NSP Tag from Scratchpad
, ppSort = fmap (.scratchpadFilterOutWorkspace) $ ppSort defaultPP
}
where
pad = "^p(4)"
icon :: String -> String
icon x = "^i(" ++ myIconPath ++ x ++ ".xbm)"
-- replace 'find' with 'repl' in 'x'
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace [] _ _ = []
replace s find repl =
if take (length find) s == find
then repl ++ (replace (drop (length find) s) find repl)
else [head s] ++ (replace (tail s) find repl)
----------------------------------------------------------------------
-- UrgencyHook
myUrgencyHook = withUrgencyHookC NoUrgencyHook urgencyConfig { suppressWhen = Focused }
----------------------------------------------------------------------
-- Run xmonad
main = do
host <- fmap nodeName getSystemID
dzen <- spawnPipe statusbarCmd
xmonad $ myUrgencyHook
$ defaultConfig
{ terminal = myTerminal
, focusFollowsMouse = myFocusFollowsMouse
, borderWidth = myBorderWidth
, modMask = myModMask
, numlockMask = myNumlockMask
, workspaces = myWorkspaces
, normalBorderColor = myInactiveBorderColor
, focusedBorderColor = myActiveBorderColor
-- , keys = \k -> myOtherKeys `M.union` keys defaultConfig k
, mouseBindings = \m -> myMouse `M.union` mouseBindings defaultConfig m
, handleEventHook = ewmhDesktopsEventHook
, layoutHook = myLayoutHook
, manageHook = scratchpadManageHook mySPRect
<+> manageDocks
<+> myManageHook
, logHook = myLogHook dzen
>> ewmhDesktopsLogHook
-- for compatibility with Java apps
, startupHook = ewmhDesktopsStartup
>> setWMName "LG3D"
>> return ()
>> checkKeymap (defaultConfig) (myKeys)
}
`additionalKeysP` myKeys
|
ahmednuaman/AS3
|
78e7ed0f6ec26c0b25b83a30faf2b0162b068d82
|
changed to app event
|
diff --git a/com/firestartermedia/lib/as3/events/SpriteEvent.as b/com/firestartermedia/lib/as3/events/AppEvent.as
similarity index 66%
rename from com/firestartermedia/lib/as3/events/SpriteEvent.as
rename to com/firestartermedia/lib/as3/events/AppEvent.as
index 69438ff..3b8c6c6 100644
--- a/com/firestartermedia/lib/as3/events/SpriteEvent.as
+++ b/com/firestartermedia/lib/as3/events/AppEvent.as
@@ -1,24 +1,29 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.events
{
import flash.events.Event;
- public class SpriteEvent extends Event
+ public class AppEvent extends Event
{
public var data:Object;
- public function SpriteEvent(type:String, data:Object=null, bubbles:Boolean=false, cancelable:Boolean=false)
+ public function AppEvent(type:String, data:Object=null, bubbles:Boolean=false, cancelable:Boolean=false)
{
super( type, bubbles, cancelable );
this.data = data;
}
+
+ override public function clone():Event
+ {
+ return new AppEvent(type, data, bubbles, cancelable);
+ }
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/puremvc/display/Sprite.as b/com/firestartermedia/lib/puremvc/display/Sprite.as
index 40764d6..6954f40 100644
--- a/com/firestartermedia/lib/puremvc/display/Sprite.as
+++ b/com/firestartermedia/lib/puremvc/display/Sprite.as
@@ -1,109 +1,109 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.puremvc.display
{
- import com.firestartermedia.lib.as3.events.SpriteEvent;
+ import com.firestartermedia.lib.as3.events.AppEvent;
import flash.display.DisplayObject;
import flash.display.Sprite;
public class Sprite extends flash.display.Sprite
{
public static const NAME:String = 'Sprite';
public var display:Boolean = true;
public var registered:Boolean = false;
public var ready:Boolean = false;
public var tweenResize:Boolean = false;
protected var tweenTime:Number = 1;
protected var readyEvent:String;
protected var resetEvent:String;
protected var trackEvent:String;
protected var stageHeight:Number;
protected var stageWidth:Number;
public function Sprite(readyEvent:String='SpriteReady', resetEvent:String='SpriteReset', trackEvent:String='SpriteTrack')
{
this.readyEvent = readyEvent;
this.resetEvent = resetEvent;
this.trackEvent = trackEvent;
registered = true;
}
public function addChildren(...children):void
{
for each ( var child:DisplayObject in children )
{
addChild( child );
}
}
override public function addChild(child:DisplayObject):DisplayObject
{
super.addChild( child );
handleResize();
return child;
}
override public function addChildAt(child:DisplayObject, index:int):DisplayObject
{
super.addChildAt( child, index );
handleResize();
return child;
}
protected function sendEvent(eventName:String, body:Object=null):void
{
- dispatchEvent( new SpriteEvent( eventName, body, true ) );
+ dispatchEvent( new AppEvent( eventName, body, true ) );
}
protected function sendReady(eventName:String=null):void
{
if ( !ready )
{
ready = true;
sendEvent( ( eventName ? eventName : readyEvent ) );
}
}
protected function sendReset(eventName:String=null):void
{
if ( !ready )
{
ready = false;
sendEvent( ( eventName ? eventName : resetEvent ) );
}
}
public function handleReset():void
{
ready = false;
sendReset();
}
public function handleResize(e:Object=null):void
{
if ( e )
{
stageHeight = e.height;
stageWidth = e.width;
}
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
d935d79bffe469bf5e0f9afa2c743280ee68c583
|
moved SpriteEvent
|
diff --git a/com/firestartermedia/lib/puremvc/events/SpriteEvent.as b/com/firestartermedia/lib/as3/events/SpriteEvent.as
similarity index 93%
rename from com/firestartermedia/lib/puremvc/events/SpriteEvent.as
rename to com/firestartermedia/lib/as3/events/SpriteEvent.as
index baf8ffb..69438ff 100644
--- a/com/firestartermedia/lib/puremvc/events/SpriteEvent.as
+++ b/com/firestartermedia/lib/as3/events/SpriteEvent.as
@@ -1,24 +1,24 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
-package com.firestartermedia.lib.puremvc.events
+package com.firestartermedia.lib.as3.events
{
import flash.events.Event;
public class SpriteEvent extends Event
{
public var data:Object;
public function SpriteEvent(type:String, data:Object=null, bubbles:Boolean=false, cancelable:Boolean=false)
{
super( type, bubbles, cancelable );
this.data = data;
}
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/puremvc/display/Sprite.as b/com/firestartermedia/lib/puremvc/display/Sprite.as
index f2e1cb7..40764d6 100644
--- a/com/firestartermedia/lib/puremvc/display/Sprite.as
+++ b/com/firestartermedia/lib/puremvc/display/Sprite.as
@@ -1,109 +1,109 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.puremvc.display
{
- import com.firestartermedia.lib.puremvc.events.SpriteEvent;
+ import com.firestartermedia.lib.as3.events.SpriteEvent;
import flash.display.DisplayObject;
import flash.display.Sprite;
public class Sprite extends flash.display.Sprite
{
public static const NAME:String = 'Sprite';
public var display:Boolean = true;
public var registered:Boolean = false;
public var ready:Boolean = false;
public var tweenResize:Boolean = false;
protected var tweenTime:Number = 1;
protected var readyEvent:String;
protected var resetEvent:String;
protected var trackEvent:String;
protected var stageHeight:Number;
protected var stageWidth:Number;
public function Sprite(readyEvent:String='SpriteReady', resetEvent:String='SpriteReset', trackEvent:String='SpriteTrack')
{
this.readyEvent = readyEvent;
this.resetEvent = resetEvent;
this.trackEvent = trackEvent;
registered = true;
}
public function addChildren(...children):void
{
for each ( var child:DisplayObject in children )
{
addChild( child );
}
}
override public function addChild(child:DisplayObject):DisplayObject
{
super.addChild( child );
handleResize();
return child;
}
override public function addChildAt(child:DisplayObject, index:int):DisplayObject
{
super.addChildAt( child, index );
handleResize();
return child;
}
protected function sendEvent(eventName:String, body:Object=null):void
{
dispatchEvent( new SpriteEvent( eventName, body, true ) );
}
protected function sendReady(eventName:String=null):void
{
if ( !ready )
{
ready = true;
sendEvent( ( eventName ? eventName : readyEvent ) );
}
}
protected function sendReset(eventName:String=null):void
{
if ( !ready )
{
ready = false;
sendEvent( ( eventName ? eventName : resetEvent ) );
}
}
public function handleReset():void
{
ready = false;
sendReset();
}
public function handleResize(e:Object=null):void
{
if ( e )
{
stageHeight = e.height;
stageWidth = e.width;
}
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
316fb30e51434dd34731405cbcbf511f3488221d
|
added gradient and shiz
|
diff --git a/com/firestartermedia/lib/as3/display/shape/Rectangle.as b/com/firestartermedia/lib/as3/display/shape/Rectangle.as
index 746ae9f..c005a62 100644
--- a/com/firestartermedia/lib/as3/display/shape/Rectangle.as
+++ b/com/firestartermedia/lib/as3/display/shape/Rectangle.as
@@ -1,32 +1,58 @@
package com.firestartermedia.lib.as3.display.shape
{
+ import flash.display.GradientType;
import flash.display.Shape;
+ import flash.geom.Matrix;
public class Rectangle extends Shape
{
- public function Rectangle(width:Number=1, height:Number=1, bgColour:uint=0xFF6600, borderColour:uint=0x000099, borderThickness:Number=1)
+ private var mat:Matrix;
+
+ public function Rectangle(width:Number=1,
+ height:Number=1,
+ bgColour:*=0xFF6600,
+ borderColour:uint=0x000099,
+ borderThickness:Number=1,
+ borderAlpha:Number=1)
{
super();
- draw( width, height, bgColour, borderColour, borderThickness );
+ draw( width, height, bgColour, borderColour, borderThickness, borderAlpha );
}
- public function draw(width:Number, height:Number, bgColour:uint, borderColour:uint, borderThickness:Number):void
+ public function draw(width:Number, height:Number, bgColour:*, borderColour:uint, borderThickness:Number, borderAlpha:Number):void
{
graphics.clear();
- graphics.beginFill( bgColour );
+
+ if (bgColour is Array)
+ {
+ if (!mat)
+ {
+ mat = new Matrix();
+
+ mat.createGradientBox(height, width, Math.PI * .5);
+ }
+
+ graphics.beginGradientFill(GradientType.LINEAR, bgColour, [1, 1], [0, 255], mat);
+ }
+ else
+ {
+ graphics.beginFill( bgColour );
+ }
if (borderThickness)
{
- graphics.lineStyle( borderThickness, borderColour );
+ graphics.lineStyle( borderThickness, borderColour, borderAlpha );
}
graphics.moveTo(0, 0);
graphics.lineTo(width, 0);
graphics.lineTo(width, height);
graphics.lineTo(0, height);
graphics.lineTo(0, 0);
graphics.endFill();
+
+ cacheAsBitmap = true;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
4cd33a0a60f9317be78b646c8900046a744dbdd4
|
added nice Rectangle class
|
diff --git a/com/firestartermedia/lib/as3/display/shape/Rectangle.as b/com/firestartermedia/lib/as3/display/shape/Rectangle.as
new file mode 100644
index 0000000..746ae9f
--- /dev/null
+++ b/com/firestartermedia/lib/as3/display/shape/Rectangle.as
@@ -0,0 +1,32 @@
+package com.firestartermedia.lib.as3.display.shape
+{
+ import flash.display.Shape;
+
+ public class Rectangle extends Shape
+ {
+ public function Rectangle(width:Number=1, height:Number=1, bgColour:uint=0xFF6600, borderColour:uint=0x000099, borderThickness:Number=1)
+ {
+ super();
+
+ draw( width, height, bgColour, borderColour, borderThickness );
+ }
+
+ public function draw(width:Number, height:Number, bgColour:uint, borderColour:uint, borderThickness:Number):void
+ {
+ graphics.clear();
+ graphics.beginFill( bgColour );
+
+ if (borderThickness)
+ {
+ graphics.lineStyle( borderThickness, borderColour );
+ }
+
+ graphics.moveTo(0, 0);
+ graphics.lineTo(width, 0);
+ graphics.lineTo(width, height);
+ graphics.lineTo(0, height);
+ graphics.lineTo(0, 0);
+ graphics.endFill();
+ }
+ }
+}
\ No newline at end of file
|
ahmednuaman/AS3
|
6c4ba085cdae0418afac3731f0b2c6e1b46ae8df
|
clearing that sheeet
|
diff --git a/com/firestartermedia/lib/as3/display/shape/Polygon.as b/com/firestartermedia/lib/as3/display/shape/Polygon.as
index 89e4f54..4381a39 100644
--- a/com/firestartermedia/lib/as3/display/shape/Polygon.as
+++ b/com/firestartermedia/lib/as3/display/shape/Polygon.as
@@ -1,52 +1,53 @@
package com.firestartermedia.lib.as3.display.shape
{
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.display.Shape;
public class Polygon extends Shape
{
public function Polygon(radius:Number=100, segments:Number=5, bgColour:uint=0xFF6600, borderColour:uint=0x000099, borderThickness:Number=1)
{
super();
draw( radius, segments, bgColour, borderColour, borderThickness );
}
protected function draw(radius:Number, segments:Number, bgColour:uint, borderColour:uint, borderThickness:Number):void
{
var coords:Array = [ ];
var ratio:Number = 360 / segments;
var vectorId:Number = 0;
var vectorRadians:Number;
var vectorX:Number;
var vectorY:Number;
+ graphics.clear();
graphics.beginFill( bgColour );
graphics.lineStyle( borderThickness, borderColour );
for ( var i:Number = 0; i <= 360; i += ratio )
{
vectorRadians = NumberUtil.toRadians( i );
vectorX = Math.sin( vectorRadians ) * radius;
vectorY = ( Math.cos( vectorRadians ) * radius );
coords[ vectorId ] = [ vectorX, vectorY ];
if ( vectorId >= 1 )
{
graphics.lineTo( vectorX, vectorY );
}
else
{
graphics.moveTo( vectorX, vectorY );
}
vectorId++;
}
graphics.endFill();
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
b1396975edebd4c8a604ab21ef7f20c89706e8e7
|
introducing a track event
|
diff --git a/com/firestartermedia/lib/puremvc/display/Sprite.as b/com/firestartermedia/lib/puremvc/display/Sprite.as
index 827d7b3..f2e1cb7 100644
--- a/com/firestartermedia/lib/puremvc/display/Sprite.as
+++ b/com/firestartermedia/lib/puremvc/display/Sprite.as
@@ -1,126 +1,109 @@
/**
- * @author Ahmed Nuaman (http://www.ahmednuaman.com)
- * @langversion 3
+ * @author Ahmed Nuaman (http://www.ahmednuaman.com)
+ * @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.puremvc.display
{
- import com.firestartermedia.lib.puremvc.events.SpriteEvent;
-
- import flash.display.DisplayObject;
- import flash.display.DisplayObjectContainer;
- import flash.display.Sprite;
+ import com.firestartermedia.lib.puremvc.events.SpriteEvent;
+
+ import flash.display.DisplayObject;
+ import flash.display.Sprite;
- public class Sprite extends flash.display.Sprite
- {
- public static const NAME:String = 'Sprite';
-
- public var display:Boolean = true;
- public var registered:Boolean = false;
- public var ready:Boolean = false;
- public var tweenResize:Boolean = false;
-
- protected var tweenTime:Number = 1;
-
- protected var readyEvent:String;
- protected var resetEvent:String;
- protected var stageHeight:Number;
- protected var stageWidth:Number;
-
- public function Sprite(readyEvent:String='SpriteReady', resetEvent:String='SpriteReset')
- {
- this.readyEvent = readyEvent;
- this.resetEvent = resetEvent;
-
- registered = true;
- }
-
- public function addChildren(...children):void
- {
- for each ( var child:DisplayObject in children )
- {
- addChild( child );
- }
- }
-
-// public function removeChildren(t:DisplayObjectContainer, ...children):void
-// {
-// if ( children.length )
-// {
-// for each ( var child:DisplayObject in children )
-// {
-// t.removeChild( child );
-// }
-// }
-// else
-// {
-// for ( var i:Number = 0; i < t.numChildren; i++ )
-// {
-// t.removeChildAt( i );
-// }
-// }
-// }
-
- override public function addChild(child:DisplayObject):DisplayObject
- {
- super.addChild( child );
-
- handleResize();
-
- return child;
- }
-
- override public function addChildAt(child:DisplayObject, index:int):DisplayObject
- {
- super.addChildAt( child, index );
-
- handleResize();
-
- return child;
- }
-
- protected function sendEvent(eventName:String, body:Object=null):void
- {
- dispatchEvent( new SpriteEvent( eventName, body, true ) );
- }
-
- protected function sendReady(eventName:String=null):void
- {
- if ( !ready )
- {
- ready = true;
-
- sendEvent( ( eventName ? eventName : readyEvent ) );
- }
- }
-
- protected function sendReset(eventName:String=null):void
- {
- if ( !ready )
- {
- ready = false;
-
- sendEvent( ( eventName ? eventName : resetEvent ) );
- }
- }
-
- public function handleReset():void
- {
- ready = false;
-
- sendReset();
- }
-
- public function handleResize(e:Object=null):void
- {
- if ( e )
- {
- stageHeight = e.height;
- stageWidth = e.width;
- }
- }
- }
+ public class Sprite extends flash.display.Sprite
+ {
+ public static const NAME:String = 'Sprite';
+
+ public var display:Boolean = true;
+ public var registered:Boolean = false;
+ public var ready:Boolean = false;
+ public var tweenResize:Boolean = false;
+
+ protected var tweenTime:Number = 1;
+
+ protected var readyEvent:String;
+ protected var resetEvent:String;
+ protected var trackEvent:String;
+ protected var stageHeight:Number;
+ protected var stageWidth:Number;
+
+ public function Sprite(readyEvent:String='SpriteReady', resetEvent:String='SpriteReset', trackEvent:String='SpriteTrack')
+ {
+ this.readyEvent = readyEvent;
+ this.resetEvent = resetEvent;
+ this.trackEvent = trackEvent;
+
+ registered = true;
+ }
+
+ public function addChildren(...children):void
+ {
+ for each ( var child:DisplayObject in children )
+ {
+ addChild( child );
+ }
+ }
+
+ override public function addChild(child:DisplayObject):DisplayObject
+ {
+ super.addChild( child );
+
+ handleResize();
+
+ return child;
+ }
+
+ override public function addChildAt(child:DisplayObject, index:int):DisplayObject
+ {
+ super.addChildAt( child, index );
+
+ handleResize();
+
+ return child;
+ }
+
+ protected function sendEvent(eventName:String, body:Object=null):void
+ {
+ dispatchEvent( new SpriteEvent( eventName, body, true ) );
+ }
+
+ protected function sendReady(eventName:String=null):void
+ {
+ if ( !ready )
+ {
+ ready = true;
+
+ sendEvent( ( eventName ? eventName : readyEvent ) );
+ }
+ }
+
+ protected function sendReset(eventName:String=null):void
+ {
+ if ( !ready )
+ {
+ ready = false;
+
+ sendEvent( ( eventName ? eventName : resetEvent ) );
+ }
+ }
+
+ public function handleReset():void
+ {
+ ready = false;
+
+ sendReset();
+ }
+
+ public function handleResize(e:Object=null):void
+ {
+ if ( e )
+ {
+ stageHeight = e.height;
+ stageWidth = e.width;
+ }
+ }
+ }
}
\ No newline at end of file
|
ahmednuaman/AS3
|
2de3180ff42e0c706adeb53c279ca019be643c28
|
added search
|
diff --git a/com/firestartermedia/lib/as3/data/gdata/YouTubeGDataService.as b/com/firestartermedia/lib/as3/data/gdata/YouTubeGDataService.as
index dfffe46..b7f553d 100644
--- a/com/firestartermedia/lib/as3/data/gdata/YouTubeGDataService.as
+++ b/com/firestartermedia/lib/as3/data/gdata/YouTubeGDataService.as
@@ -1,213 +1,220 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.data.gdata
{
import com.firestartermedia.lib.as3.data.DataService;
import com.firestartermedia.lib.as3.events.DataServiceEvent;
import com.firestartermedia.lib.as3.utils.YouTubeUtil;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
public class YouTubeGDataService extends DataService
{
public var GDATA_URL:String = 'http://gdata.youtube.com/feeds/api/';
public var PLAYLISTS_URL:String = GDATA_URL + 'playlists';
public var USERS_URL:String = GDATA_URL + 'users';
public var VIDEOS_URL:String = GDATA_URL + 'videos';
private var currentPlaylistEntries:Number;
private var playlistEntries:Array;
private var playlistId:String;
private var playlistSearch:String;
public function YouTubeGDataService()
{
super( DataServiceEvent.LOADING, DataServiceEvent.LOADED, DataServiceEvent.READY, DataService.TYPE_JSON );
}
public function getVideoData(videoId:String):void
{
var request:URLRequest = new URLRequest( VIDEOS_URL + '/' + videoId + '?alt=json' );
load( request );
}
public function getPlaylistData(playlistId:String, startIndex:Number=1):void
{
var request:URLRequest = new URLRequest( PLAYLISTS_URL + '/' + playlistId + '?v=2&max-results=50&alt=json&start-index=' + startIndex );
load( request );
}
+ public function searchFor(query:String):void
+ {
+ var request:URLRequest = new URLRequest( VIDEOS_URL + '/?q=' + escape(query) + '&alt=json' );
+
+ load( request );
+ }
+
public function searchPlaylistData(playlistId:String, playlistSearch:String):void
{
this.playlistId = playlistId;
this.playlistSearch = playlistSearch;
handleReady = false;
currentPlaylistEntries = 1;
playlistEntries = [ ];
addEventListener( DataServiceEvent.LOADED, handleSearchPlaylistDataComplete );
getPlaylistData( playlistId );
}
private function handleSearchPlaylistDataComplete(e:DataServiceEvent):void
{
var data:XML = e.data as XML;
var length:Number = data..*::itemsPerPage;
var total:Number = data..*::totalResults;
var entries:Array = YouTubeUtil.cleanGDataFeed( data );
for each ( var entry:Object in entries )
{
if ( playlistEntries.length <= total )
{
playlistEntries.push( entry );
}
}
currentPlaylistEntries += length;
if ( currentPlaylistEntries >= total )
{
searchThroughPlaylistData();
}
else
{
getPlaylistData( playlistId, currentPlaylistEntries );
}
}
private function searchThroughPlaylistData():void
{
var matchEntries:Array = [ ];
for each ( var entry:Object in playlistEntries )
{
if (
entry.title.toLowerCase().search( playlistSearch.toLowerCase() ) != -1 ||
entry.description.toLowerCase().search( playlistSearch.toLowerCase() ) != -1 ||
entry.keywords.toLowerCase().search( playlistSearch.toLowerCase() ) != -1
)
{
matchEntries.push( entry );
}
}
dispatchEvent( new DataServiceEvent( DataServiceEvent.READY, { entries: matchEntries } ) );
}
public function getUserVideos(username:String, startIndex:Number=1, max:Number=50):void
{
var request:URLRequest = new URLRequest( VIDEOS_URL + '?v=2&alt=json&max-results=' + max + '&start-index=' + startIndex + '&author=' + username );
load( request );
}
public function getAuthedUserVideos(token:String, devkey:String, startIndex:Number=1, max:Number=50):void
{
var request:URLRequest = new URLRequest( USERS_URL + '/default/uploads?alt=json' );
request.contentType = 'application/atom+xml; charset=UTF-8';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ),
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ),
new URLRequestHeader( 'GData-Version', '2' ),
new URLRequestHeader( 'X-GData-Key', 'key=' + devkey ) ];
request.data = new URLVariables( 'key=' + devkey );
load( request );
}
public function subscribeToUser(username:String, token:String, devkey:String):void
{
var request:URLRequest = new URLRequest( USERS_URL + '/default/subscriptions' );
request.contentType = 'application/atom+xml; charset=UTF-8';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ /* new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ), */
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ),
new URLRequestHeader( 'GData-Version', '2' ),
new URLRequestHeader( 'X-GData-Key', 'key=' + devkey ) ];
request.data = '<?xml version="1.0" encoding="UTF-8"?>' +
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:yt="http://gdata.youtube.com/schemas/2007">' +
'<category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat" term="channel"/>' +
'<yt:username>' + username + '</yt:username>' +
'</entry>';
load( request );
}
public function rateVideo(videoId:String, rating:Number, token:String, devkey:String):void
{
var request:URLRequest = new URLRequest( VIDEOS_URL + '/' + videoId + '/ratings' );
request.contentType = 'application/atom+xml; charset=UTF-8';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ /* new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ), */
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ),
new URLRequestHeader( 'GData-Version', '2' ),
new URLRequestHeader( 'X-GData-Key', 'key=' + devkey ) ];
request.data = '<?xml version="1.0" encoding="UTF-8"?>' +
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005">' +
'<gd:rating value="' + rating + '" min="1" max="5"/>' +
'</entry>';
load( request );
}
public function exchangeForSessionToken(token:String):void
{
var request:URLRequest = new URLRequest( 'https://accounts.googleapis.com/accounts/AuthSubSessionToken' );
request.contentType = 'application/x-www-form-urlencoded';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ /* new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ), */
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ) ];
request.data = new URLVariables( 'foo=bar' );
load( request );
}
public function getUploadToken(token:String, devkey:String, title:String, description:String, category:String, keywords:String):void
{
var request:URLRequest = new URLRequest( GDATA_URL.replace( '/feeds/api/', '/action/GetUploadToken' ) );
request.contentType = 'application/atom+xml; charset=UTF-8';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ /* new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ), */
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ),
new URLRequestHeader( 'GData-Version', '2' ),
new URLRequestHeader( 'X-GData-Key', 'key=' + devkey ) ];
request.data = '<?xml version="1.0" encoding="UTF-8"?>' +
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">' +
'<media:group><media:title type="plain">' + title + '</media:title>' +
'<media:description type="plain">' + description + '</media:description>' +
'<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">' + category + '</media:category>' +
'<media:keywords>' + keywords + '</media:keywords>' +
'</media:group></entry>';
load( request );
}
private function load(request:URLRequest):void
{
loader.load( request );
dispatchEvent( new DataServiceEvent( DataServiceEvent.LOADING ) );
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
704e01340259050e10ef4d12d272e74a9c154b6c
|
fixed issue with duration
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index 5a2df67..54f2ede 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,283 +1,279 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2000;
public var loop:Boolean = false;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String=null, autoPlay:Boolean=false)
{
super( this );
this.autoPlay = autoPlay;
if ( t )
{
play( t );
}
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
var d:Object;
try
{
d = sound.id3;
}
catch (e:*)
{
d = { };
}
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, d ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
private function handleSoundOpen(e:Event):void
{
if ( !autoPlay )
{
pause();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
sound.addEventListener( Event.OPEN, handleSoundOpen );
sound.load( request, context );
channel = sound.play( currentPosition, loop ? -1 : 0 );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
try
{
sound.close();
}
catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
if ( channel )
{
channel.stop();
}
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel.stop();
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
- trace(e);
-
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
/*if ( loop )
{
channel = sound.play( 0 );
}*/
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
- trace( channel.position, sound.length );
-
time.current = channel ? channel.position / 1000 : 0;
- time.total = sound.length / 1000;
+ time.total = ( sound.length / sound.bytesLoaded * sound.bytesTotal ) / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
-
+
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
eeba86212c65f37362b1da8bbe13b8d93aa48546
|
added better catch for accessing sound data
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index b8a7276..5a2df67 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,272 +1,283 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
- public var bufferTime:Number = 2;
+ public var bufferTime:Number = 2000;
public var loop:Boolean = false;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String=null, autoPlay:Boolean=false)
{
super( this );
this.autoPlay = autoPlay;
if ( t )
{
play( t );
}
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
- dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
+ var d:Object;
+
+ try
+ {
+ d = sound.id3;
+ }
+ catch (e:*)
+ {
+ d = { };
+ }
+
+ dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, d ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
private function handleSoundOpen(e:Event):void
{
if ( !autoPlay )
{
pause();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
sound.addEventListener( Event.OPEN, handleSoundOpen );
sound.load( request, context );
channel = sound.play( currentPosition, loop ? -1 : 0 );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
try
{
sound.close();
}
catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
if ( channel )
{
channel.stop();
}
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel.stop();
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
trace(e);
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
/*if ( loop )
{
channel = sound.play( 0 );
}*/
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
trace( channel.position, sound.length );
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
7f052a1a1107fa6e49ff99e8cc4fd628db651cd0
|
added unique sorting
|
diff --git a/com/firestartermedia/lib/as3/utils/ArrayUtil.as b/com/firestartermedia/lib/as3/utils/ArrayUtil.as
index 7873abd..7ad225a 100644
--- a/com/firestartermedia/lib/as3/utils/ArrayUtil.as
+++ b/com/firestartermedia/lib/as3/utils/ArrayUtil.as
@@ -1,77 +1,97 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
+ import flash.utils.Dictionary;
+
public class ArrayUtil
{
public static function shuffle(array:Array):Array
{
var i:Number = array.length;
var j:Number;
var t1:*;
var t2:*;
if ( i == 0 )
{
return [ ];
}
else
{
while ( --i )
{
j = Math.floor( Math.random() * ( i + 1 ) );
t1 = array[ i ];
t2 = array[ j ];
array[ i ] = t2;
array[ j ] = t1;
}
return array;
}
}
public static function search(array:Array, value:Object):Number
{
var found:Boolean = false;
for ( var i:Number = 0; i < array.length; i++)
{
if ( array[ i ] == value )
{
found = true;
break;
}
}
return ( found ? i : -1 );
}
public static function toArray(data:Object):Array
{
var array:Array = [ ];
for each ( var item:Object in data )
{
array.push( item );
}
return array;
}
- public static function randomEntry(array:Array):Object
+ public static function randomEntry(array:Array):*
{
var i:Number = Math.round( Math.random() * ( array.length - 1 ) );
return array[ i ];
}
+
+ public static function unique(array:Array):Array
+ {
+ var n:Array = [ ];
+ var o:Dictionary = new Dictionary();
+
+ for ( var i:Number = 0; i < array.length; i++)
+ {
+ o[ array[ i ] ] = true;
+ }
+
+ for ( var p:Object in o )
+ {
+ n.push( p );
+ }
+
+ return n;
+ }
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
9f82cf67d22d34fed6b123cdcfcca287ed981a0a
|
made some updates
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index faf74ac..b8a7276 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,268 +1,272 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
public var loop:Boolean = false;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String=null, autoPlay:Boolean=false)
{
super( this );
this.autoPlay = autoPlay;
if ( t )
{
play( t );
}
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
private function handleSoundOpen(e:Event):void
{
if ( !autoPlay )
{
pause();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
sound.addEventListener( Event.OPEN, handleSoundOpen );
sound.load( request, context );
channel = sound.play( currentPosition, loop ? -1 : 0 );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
try
{
sound.close();
}
catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
if ( channel )
{
channel.stop();
}
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel.stop();
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
+ trace(e);
+
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
/*if ( loop )
{
channel = sound.play( 0 );
}*/
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
+ trace( channel.position, sound.length );
+
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/as3/utils/BitmapUtil.as b/com/firestartermedia/lib/as3/utils/BitmapUtil.as
index 5a28f39..a7e321b 100644
--- a/com/firestartermedia/lib/as3/utils/BitmapUtil.as
+++ b/com/firestartermedia/lib/as3/utils/BitmapUtil.as
@@ -1,46 +1,47 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.PixelSnapping;
+ import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
public class BitmapUtil
{
public static function flatten(source:*):BitmapData
{
return grab( source, new Rectangle( 0, 0, source.width, source.height ) );
}
- public static function grab(source:*, rect:Rectangle, smoothing:Boolean=true):BitmapData
+ public static function grab(source:*, rect:Rectangle, matrix:Matrix=null):BitmapData
{
var draw:BitmapData = new BitmapData( source.width, source.height, true, 0 );
var copy:BitmapData = new BitmapData( rect.width, rect.height, true, 0 );
- draw.draw( source, null, null, null, null, smoothing );
+ draw.draw( source, matrix, null, null, null, true );
copy.copyPixels( draw, rect, new Point( 0, 0 ) );
draw.dispose();
return copy;
}
- public static function clone(source:*, x:Number=0, y:Number=0, w:Number=0, h:Number=0):Bitmap
+ public static function clone(source:*, x:Number=0, y:Number=0, w:Number=0, h:Number=0, m:Matrix=null):Bitmap
{
h = h || source.height;
w = w || source.width;
- return new Bitmap( grab( source, new Rectangle( x, y, w, h ) ), PixelSnapping.AUTO, true );
+ return new Bitmap( grab( source, new Rectangle( x, y, w, h ), m ), PixelSnapping.AUTO, true );
}
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as b/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
index dd02f2f..4415b0a 100644
--- a/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
+++ b/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
@@ -1,147 +1,142 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class DisplayObjectUtil
{
public static function removeChildren(target:Object):void
{
while ( target.numChildren )
{
target.removeChildAt( target.numChildren - 1 );
}
}
public static function addChildren(target:DisplayObjectContainer, ...children):void
{
for each ( var child:DisplayObject in children )
{
target.addChild( child );
}
}
public static function getChildren(target:DisplayObjectContainer):Array
{
var children:Array = [ ];
for ( var i:Number; target.numChildren < i; i++ )
{
children.push( target.getChildAt( i ) );
}
return children;
}
public static function loadMovie(url:String, parent:DisplayObjectContainer=null, completeFunction:Function=null, applicationDomain:ApplicationDomain=null, checkPolicyFile:Boolean=false):Loader
{
var request:URLRequest = new URLRequest( url );
var context:LoaderContext = new LoaderContext( checkPolicyFile, ( applicationDomain ||= ApplicationDomain.currentDomain ) );
var loader:Loader = new Loader();
if ( parent != null )
{
parent.addChild( loader );
}
if ( completeFunction != null )
{
loader.contentLoaderInfo.addEventListener( Event.COMPLETE, completeFunction, false, 0, true );
}
- try
- {
- loader.load( request, context );
- }
- catch (e:*)
- { }
+ loader.load( request, context );
return loader;
}
public static function scale(target:DisplayObject, width:Number=0, height:Number=0):Number
{
/*var targetHeight:Number = ( height > 0 ? height : target.height );
var targetWidth:Number = targetHeight * ( target.width / target.height );
if ( targetWidth > target.width )
{
targetWidth = ( width > 0 ? width : target.width );
targetHeight = targetWidth * ( target.height / target.width );
}
target.height = targetHeight;
target.width = targetWidth;*/
var scaleHeight:Number = height / target.height;
var scaleWidth:Number = width / target.width;
var scale:Number = ( scaleHeight <= scaleWidth ? scaleHeight : scaleWidth );
/*target.scaleX = scale;
target.scaleY = scale;*/
target.height = target.height * scale;
target.width = target.width * scale;
return scale;
}
public static function eachChild(target:DisplayObjectContainer, func:Function):Array
{
var funcReturn:Array = [ ];
for ( var i:Number = 0; i < target.numChildren; i++ )
{
funcReturn.push( func.apply( null, [ target.getChildAt( i ) ] ) );
}
return funcReturn;
}
public static function centerRotate(target:DisplayObject, center:Point, degrees:Number):void
{
var m:Matrix = target.transform.matrix;
m.tx -= center.x;
m.ty -= center.y;
m.rotate( NumberUtil.toRadians( degrees ) );
m.tx += center.x;
m.ty += center.y;
target.transform.matrix = m;
}
public static function changeColour(target:DisplayObject, colour:*):void
{
var trans:ColorTransform = target.transform.colorTransform;
var c:uint = ( colour is uint ? colour : NumberUtil.toUint( colour ) );
trans.color = c;
target.transform.colorTransform = trans;
}
public static function revertColour(target:DisplayObject):void
{
target.transform.colorTransform = new ColorTransform();
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
3bb90c6a4d507cde7fa564e0153cc067fa5fe7f5
|
allowed setting of x, y, width and height
|
diff --git a/com/firestartermedia/lib/as3/utils/BitmapUtil.as b/com/firestartermedia/lib/as3/utils/BitmapUtil.as
index 66ed64c..5a28f39 100644
--- a/com/firestartermedia/lib/as3/utils/BitmapUtil.as
+++ b/com/firestartermedia/lib/as3/utils/BitmapUtil.as
@@ -1,43 +1,46 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.PixelSnapping;
import flash.geom.Point;
import flash.geom.Rectangle;
public class BitmapUtil
{
public static function flatten(source:*):BitmapData
{
return grab( source, new Rectangle( 0, 0, source.width, source.height ) );
}
public static function grab(source:*, rect:Rectangle, smoothing:Boolean=true):BitmapData
{
var draw:BitmapData = new BitmapData( source.width, source.height, true, 0 );
var copy:BitmapData = new BitmapData( rect.width, rect.height, true, 0 );
draw.draw( source, null, null, null, null, smoothing );
copy.copyPixels( draw, rect, new Point( 0, 0 ) );
draw.dispose();
return copy;
}
- public static function clone(source:*):Bitmap
+ public static function clone(source:*, x:Number=0, y:Number=0, w:Number=0, h:Number=0):Bitmap
{
- return new Bitmap( grab( source, new Rectangle( 0, 0, source.width, source.height ) ), PixelSnapping.AUTO, true );
+ h = h || source.height;
+ w = w || source.width;
+
+ return new Bitmap( grab( source, new Rectangle( x, y, w, h ) ), PixelSnapping.AUTO, true );
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
70de4c7dd3f1ae973b2f18d3039837e1e94527d9
|
opened removechildren to other containers, such as object3d ones
|
diff --git a/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as b/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
index dffc4cc..dd02f2f 100644
--- a/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
+++ b/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
@@ -1,147 +1,147 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class DisplayObjectUtil
{
- public static function removeChildren(target:DisplayObjectContainer):void
+ public static function removeChildren(target:Object):void
{
while ( target.numChildren )
{
target.removeChildAt( target.numChildren - 1 );
}
}
public static function addChildren(target:DisplayObjectContainer, ...children):void
{
for each ( var child:DisplayObject in children )
{
target.addChild( child );
}
}
public static function getChildren(target:DisplayObjectContainer):Array
{
var children:Array = [ ];
for ( var i:Number; target.numChildren < i; i++ )
{
children.push( target.getChildAt( i ) );
}
return children;
}
public static function loadMovie(url:String, parent:DisplayObjectContainer=null, completeFunction:Function=null, applicationDomain:ApplicationDomain=null, checkPolicyFile:Boolean=false):Loader
{
var request:URLRequest = new URLRequest( url );
var context:LoaderContext = new LoaderContext( checkPolicyFile, ( applicationDomain ||= ApplicationDomain.currentDomain ) );
var loader:Loader = new Loader();
if ( parent != null )
{
parent.addChild( loader );
}
if ( completeFunction != null )
{
loader.contentLoaderInfo.addEventListener( Event.COMPLETE, completeFunction, false, 0, true );
}
try
{
loader.load( request, context );
}
catch (e:*)
{ }
return loader;
}
public static function scale(target:DisplayObject, width:Number=0, height:Number=0):Number
{
/*var targetHeight:Number = ( height > 0 ? height : target.height );
var targetWidth:Number = targetHeight * ( target.width / target.height );
if ( targetWidth > target.width )
{
targetWidth = ( width > 0 ? width : target.width );
targetHeight = targetWidth * ( target.height / target.width );
}
target.height = targetHeight;
target.width = targetWidth;*/
var scaleHeight:Number = height / target.height;
var scaleWidth:Number = width / target.width;
var scale:Number = ( scaleHeight <= scaleWidth ? scaleHeight : scaleWidth );
/*target.scaleX = scale;
target.scaleY = scale;*/
target.height = target.height * scale;
target.width = target.width * scale;
return scale;
}
public static function eachChild(target:DisplayObjectContainer, func:Function):Array
{
var funcReturn:Array = [ ];
for ( var i:Number = 0; i < target.numChildren; i++ )
{
funcReturn.push( func.apply( null, [ target.getChildAt( i ) ] ) );
}
return funcReturn;
}
public static function centerRotate(target:DisplayObject, center:Point, degrees:Number):void
{
var m:Matrix = target.transform.matrix;
m.tx -= center.x;
m.ty -= center.y;
m.rotate( NumberUtil.toRadians( degrees ) );
m.tx += center.x;
m.ty += center.y;
target.transform.matrix = m;
}
public static function changeColour(target:DisplayObject, colour:*):void
{
var trans:ColorTransform = target.transform.colorTransform;
var c:uint = ( colour is uint ? colour : NumberUtil.toUint( colour ) );
trans.color = c;
target.transform.colorTransform = trans;
}
public static function revertColour(target:DisplayObject):void
{
target.transform.colorTransform = new ColorTransform();
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
2f7bfe99e80aa2e3808a29c4384b6ba24df87c9e
|
added nice truncation util
|
diff --git a/com/firestartermedia/lib/as3/utils/StringUtil.as b/com/firestartermedia/lib/as3/utils/StringUtil.as
index 98c3a44..f61c93a 100644
--- a/com/firestartermedia/lib/as3/utils/StringUtil.as
+++ b/com/firestartermedia/lib/as3/utils/StringUtil.as
@@ -1,47 +1,52 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
public class StringUtil
{
public static function removeSpaces(string:String):String
{
return string.replace( /\s*/gim, '' );
}
public static function multiply(string:String, times:Number):String
{
var result:String = '';
for ( var i:Number = 0; i < times; i++ )
{
result = result + string;
}
return result;
}
public static function print(obj:*, level:Number=0):void
{
var tabs:String = StringUtil.multiply( "\t", level );
for ( var prop:String in obj )
{
trace( tabs + '[' + prop + '] -> ' + obj[ prop ] );
StringUtil.print( obj[ prop ], level + 1 );
}
}
public static function trim(s:String):String
{
return s.replace( /^\s+|\s+$/gs, '' );
}
+
+ public static function truncate(s:String, l:Number, a:String=''):String
+ {
+ return s.length <= l ? s : s.substr( 0, l ) + a;
+ }
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
34b0613a87fb78aa8eb03333ba5bda39f9ef1c31
|
added random entry util where it gets a random child in an array
|
diff --git a/com/firestartermedia/lib/as3/utils/ArrayUtil.as b/com/firestartermedia/lib/as3/utils/ArrayUtil.as
index 4dc679a..7873abd 100644
--- a/com/firestartermedia/lib/as3/utils/ArrayUtil.as
+++ b/com/firestartermedia/lib/as3/utils/ArrayUtil.as
@@ -1,70 +1,77 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
public class ArrayUtil
{
public static function shuffle(array:Array):Array
{
var i:Number = array.length;
var j:Number;
var t1:*;
var t2:*;
if ( i == 0 )
{
return [ ];
}
else
{
while ( --i )
{
j = Math.floor( Math.random() * ( i + 1 ) );
t1 = array[ i ];
t2 = array[ j ];
array[ i ] = t2;
array[ j ] = t1;
}
return array;
}
}
public static function search(array:Array, value:Object):Number
{
var found:Boolean = false;
for ( var i:Number = 0; i < array.length; i++)
{
if ( array[ i ] == value )
{
found = true;
break;
}
}
return ( found ? i : -1 );
}
public static function toArray(data:Object):Array
{
var array:Array = [ ];
for each ( var item:Object in data )
{
array.push( item );
}
return array;
}
+
+ public static function randomEntry(array:Array):Object
+ {
+ var i:Number = Math.round( Math.random() * ( array.length - 1 ) );
+
+ return array[ i ];
+ }
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
6ef9b2761595ce573ae3daf762473b819f2c698c
|
added a default to body
|
diff --git a/com/firestartermedia/lib/puremvc/patterns/Facade.as b/com/firestartermedia/lib/puremvc/patterns/Facade.as
index d04f73b..647b32c 100644
--- a/com/firestartermedia/lib/puremvc/patterns/Facade.as
+++ b/com/firestartermedia/lib/puremvc/patterns/Facade.as
@@ -1,57 +1,57 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.puremvc.patterns
{
import org.puremvc.as3.patterns.facade.Facade;
import org.puremvc.as3.patterns.observer.Notification;
public class Facade extends org.puremvc.as3.patterns.facade.Facade
{
protected var faultEvent:String;
protected var resizeEvent:String;
protected var startupEvent:String;
protected var trackEvent:String;
public function Facade(startupEvent:String, faultEvent:String, resizeEvent:String, trackEvent:String)
{
this.faultEvent = faultEvent;
this.resizeEvent = resizeEvent;
this.startupEvent = startupEvent;
this.trackEvent = trackEvent;
}
public function startup(stage:Object):void
{
sendNotification( startupEvent, stage );
}
public function sendResize(width:Number, height:Number):void
{
sendNotification( resizeEvent, { width: width, height: height } );
}
public function registerCommands(commands:Array, target:Class):void
{
for each ( var command:String in commands )
{
registerCommand( command, target );
}
}
override public function sendNotification(notificationName:String, body:Object=null, type:String=null):void
{
if ( notificationName !== faultEvent && notificationName !== resizeEvent && notificationName !== trackEvent )
{
- sendNotification( trackEvent, { name: notificationName, body: body } );
+ sendNotification( trackEvent, { name: notificationName, body: body || { } } );
}
notifyObservers( new Notification( notificationName, body, type ) );
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
e319e73bf51ad327598ee665975f9884e128501c
|
not using view anymore, it was a stupid idea
|
diff --git a/com/firestartermedia/lib/puremvc/patterns/ApplicationMediator.as b/com/firestartermedia/lib/puremvc/patterns/ApplicationMediator.as
index d52f35f..fb59bea 100644
--- a/com/firestartermedia/lib/puremvc/patterns/ApplicationMediator.as
+++ b/com/firestartermedia/lib/puremvc/patterns/ApplicationMediator.as
@@ -1,136 +1,136 @@
package com.firestartermedia.lib.puremvc.patterns
{
import com.firestartermedia.lib.as3.utils.ArrayUtil;
import flash.utils.getDefinitionByName;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.INotification;
public class ApplicationMediator extends Mediator implements IMediator
{
protected var classPath:String = 'com.firestartermedia.view.';
protected var excludedMediators:Array = [ ];
protected var tabbedMediators:Array = [ ];
protected var viewNamingHide:String = 'Hide';
protected var viewNamingMediator:String = 'Mediator';
protected var viewNamingShow:String = 'Show';
protected var currentMediator:String;
public function ApplicationMediator(name:String=null, viewComponent:Object=null)
{
super( name, viewComponent );
}
protected function addMediator(mediator:Object, data:Object=null):void
{
var m:Object;
if ( !mediator.hasOwnProperty( 'NAME' ) )
{
mediator = getDefinitionByName( classPath + mediator.toString().split( '-' )[ 0 ] ) as Class
}
if ( !facade.hasMediator( mediator.NAME ) )
{
removeOtherMediators( mediator.NAME );
facade.registerMediator( new mediator() );
m = facade.retrieveMediator( mediator.NAME );
if ( !m )
{
sendNotification( 'ApplicationFacadeFault', 'Well it looks like ' + mediator.NAME + ' hasn\'t loaded correctly' );
return;
}
try
{
- view.addChild( m.getViewComponent() );
+ viewComponent.addChild( m.getViewComponent() );
}
catch (e:*)
{
sendNotification( 'ApplicationFacadeFault', 'Failed to add ' + mediator.NAME + '\'s view' );
}
if ( m.hasOwnProperty( 'data' ) )
{
m.data = data;
}
currentMediator = mediator.NAME;
}
}
protected function removeMediator(mediator:Object):void
{
var m:Object;
if ( !mediator.hasOwnProperty( 'NAME' ) )
{
mediator = getDefinitionByName( classPath + mediator.toString().split( '-' )[ 0 ] ) as Class
}
if ( facade.hasMediator( mediator.NAME ) )
{
m = facade.retrieveMediator( mediator.NAME );
if ( !m )
{
sendNotification( 'ApplicationFacadeFault', 'Well it looks like ' + mediator.NAME + ' hasn\'t loaded correctly' );
return;
}
try
{
- view.removeChild( m.getViewComponent() );
+ viewComponent.removeChild( m.getViewComponent() );
}
catch (e:*)
{
sendNotification( 'ApplicationFacadeFault', 'Failed to remove ' + mediator.NAME + '\'s view' );
}
facade.removeMediator( mediator.NAME );
}
}
protected function removeOtherMediators(mediator:String=''):void
{
if ( ( ArrayUtil.search( excludedMediators, mediator ) === -1 && ArrayUtil.search( tabbedMediators, mediator ) !== -1 ) || mediator === '' )
{
for each ( var m:String in tabbedMediators )
{
if ( m !== mediator )
{
removeMediator( getDefinitionByName( classPath + m ) as Class );
}
}
}
}
protected function handleSectionChange(notification:INotification):void
{
var name:String = notification.getName();
var data:Object = notification.getBody();
var mediator:String = name.replace( viewNamingHide, '' ).replace( viewNamingShow, '' ) + viewNamingMediator;
if ( name.indexOf( viewNamingHide ) !== -1 )
{
removeMediator( mediator );
}
else
{
addMediator( mediator, data );
}
}
protected function mediator(name:String):*
{
return facade.retrieveMediator( name );
}
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/puremvc/patterns/Mediator.as b/com/firestartermedia/lib/puremvc/patterns/Mediator.as
index cb04fca..e801710 100644
--- a/com/firestartermedia/lib/puremvc/patterns/Mediator.as
+++ b/com/firestartermedia/lib/puremvc/patterns/Mediator.as
@@ -1,109 +1,105 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.puremvc.patterns
{
import com.adobe.utils.ArrayUtil;
import com.firestartermedia.lib.puremvc.vo.MediatorNotificationInterestVO;
import flash.utils.Dictionary;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class Mediator extends org.puremvc.as3.patterns.mediator.Mediator
{
protected var notificationInterests:Array = [ ];
protected var notificationHandlers:Dictionary = new Dictionary();
- protected var view:Object;
-
public function Mediator(name:String=null, viewComponent:Object=null)
{
super( name, viewComponent );
- view = viewComponent;
-
declareNotificationInterest( 'ApplicationFacadeResize', handleResize );
trackEvent( 'Created ' + mediatorName );
}
override public function onRegister():void
{
trackEvent( 'Registered ' + mediatorName );
}
override public function onRemove():void
{
trackEvent( 'Removed ' + mediatorName );
onReset();
}
private function onReset():void
{
- if ( view.hasOwnProperty( 'handleReset' ) )
+ if ( viewComponent.hasOwnProperty( 'handleReset' ) )
{
trackEvent( 'Reset ' + mediatorName );
- view.handleReset();
+ viewComponent.handleReset();
}
}
public function trackEvent(event:String):void
{
sendNotification( 'ApplicationFacadeTrack', event );
}
public function sendEvent(event:*):void
{
sendNotification( event.type, event.data );
}
public function declareNotificationInterest(notification:String, func:Function):void
{
notificationInterests.push( notification );
notificationInterests = ArrayUtil.createUniqueCopy( notificationInterests );
notificationHandlers[ notification ] = func;
}
public function declareNotificationInterests(interests:Array):void
{
for each ( var interest:MediatorNotificationInterestVO in interests )
{
declareNotificationInterest( interest.notification, interest.func );
}
}
override public function listNotificationInterests():Array
{
return notificationInterests;
}
override public function handleNotification(notification:INotification):void
{
notificationHandlers[ notification.getName() ].apply( null, [ notification ] );
}
public function handleReset(n:INotification):void
{
onReset();
}
public function handleResize(n:INotification):void
{
- if ( view.hasOwnProperty( 'handleResize' ) )
+ if ( viewComponent.hasOwnProperty( 'handleResize' ) )
{
- view.handleResize( n.getBody() );
+ viewComponent.handleResize( n.getBody() );
}
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
9f310cb2c5622e88778662251482c9432308b3e1
|
changed from xml to json
|
diff --git a/com/firestartermedia/lib/as3/data/gdata/YouTubeGDataService.as b/com/firestartermedia/lib/as3/data/gdata/YouTubeGDataService.as
index d9b8223..dfffe46 100644
--- a/com/firestartermedia/lib/as3/data/gdata/YouTubeGDataService.as
+++ b/com/firestartermedia/lib/as3/data/gdata/YouTubeGDataService.as
@@ -1,213 +1,213 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.data.gdata
{
import com.firestartermedia.lib.as3.data.DataService;
import com.firestartermedia.lib.as3.events.DataServiceEvent;
import com.firestartermedia.lib.as3.utils.YouTubeUtil;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
public class YouTubeGDataService extends DataService
{
public var GDATA_URL:String = 'http://gdata.youtube.com/feeds/api/';
public var PLAYLISTS_URL:String = GDATA_URL + 'playlists';
public var USERS_URL:String = GDATA_URL + 'users';
public var VIDEOS_URL:String = GDATA_URL + 'videos';
private var currentPlaylistEntries:Number;
private var playlistEntries:Array;
private var playlistId:String;
private var playlistSearch:String;
public function YouTubeGDataService()
{
- super( DataServiceEvent.LOADING, DataServiceEvent.LOADED, DataServiceEvent.READY );
+ super( DataServiceEvent.LOADING, DataServiceEvent.LOADED, DataServiceEvent.READY, DataService.TYPE_JSON );
}
public function getVideoData(videoId:String):void
{
- var request:URLRequest = new URLRequest( VIDEOS_URL + '/' + videoId );
+ var request:URLRequest = new URLRequest( VIDEOS_URL + '/' + videoId + '?alt=json' );
load( request );
}
public function getPlaylistData(playlistId:String, startIndex:Number=1):void
{
- var request:URLRequest = new URLRequest( PLAYLISTS_URL + '/' + playlistId + '?v=2&max-results=50&start-index=' + startIndex );
+ var request:URLRequest = new URLRequest( PLAYLISTS_URL + '/' + playlistId + '?v=2&max-results=50&alt=json&start-index=' + startIndex );
load( request );
}
public function searchPlaylistData(playlistId:String, playlistSearch:String):void
{
this.playlistId = playlistId;
this.playlistSearch = playlistSearch;
handleReady = false;
currentPlaylistEntries = 1;
playlistEntries = [ ];
addEventListener( DataServiceEvent.LOADED, handleSearchPlaylistDataComplete );
getPlaylistData( playlistId );
}
private function handleSearchPlaylistDataComplete(e:DataServiceEvent):void
{
var data:XML = e.data as XML;
var length:Number = data..*::itemsPerPage;
var total:Number = data..*::totalResults;
var entries:Array = YouTubeUtil.cleanGDataFeed( data );
for each ( var entry:Object in entries )
{
if ( playlistEntries.length <= total )
{
playlistEntries.push( entry );
}
}
currentPlaylistEntries += length;
if ( currentPlaylistEntries >= total )
{
searchThroughPlaylistData();
}
else
{
getPlaylistData( playlistId, currentPlaylistEntries );
}
}
private function searchThroughPlaylistData():void
{
var matchEntries:Array = [ ];
for each ( var entry:Object in playlistEntries )
{
if (
entry.title.toLowerCase().search( playlistSearch.toLowerCase() ) != -1 ||
entry.description.toLowerCase().search( playlistSearch.toLowerCase() ) != -1 ||
entry.keywords.toLowerCase().search( playlistSearch.toLowerCase() ) != -1
)
{
matchEntries.push( entry );
}
}
dispatchEvent( new DataServiceEvent( DataServiceEvent.READY, { entries: matchEntries } ) );
}
public function getUserVideos(username:String, startIndex:Number=1, max:Number=50):void
{
- var request:URLRequest = new URLRequest( VIDEOS_URL + '?v=2&max-results=' + max + '&start-index=' + startIndex + '&author=' + username );
+ var request:URLRequest = new URLRequest( VIDEOS_URL + '?v=2&alt=json&max-results=' + max + '&start-index=' + startIndex + '&author=' + username );
load( request );
}
public function getAuthedUserVideos(token:String, devkey:String, startIndex:Number=1, max:Number=50):void
{
- var request:URLRequest = new URLRequest( USERS_URL + '/default/uploads' );
+ var request:URLRequest = new URLRequest( USERS_URL + '/default/uploads?alt=json' );
request.contentType = 'application/atom+xml; charset=UTF-8';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ),
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ),
new URLRequestHeader( 'GData-Version', '2' ),
new URLRequestHeader( 'X-GData-Key', 'key=' + devkey ) ];
request.data = new URLVariables( 'key=' + devkey );
load( request );
}
public function subscribeToUser(username:String, token:String, devkey:String):void
{
var request:URLRequest = new URLRequest( USERS_URL + '/default/subscriptions' );
request.contentType = 'application/atom+xml; charset=UTF-8';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ /* new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ), */
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ),
new URLRequestHeader( 'GData-Version', '2' ),
new URLRequestHeader( 'X-GData-Key', 'key=' + devkey ) ];
request.data = '<?xml version="1.0" encoding="UTF-8"?>' +
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:yt="http://gdata.youtube.com/schemas/2007">' +
'<category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat" term="channel"/>' +
'<yt:username>' + username + '</yt:username>' +
'</entry>';
load( request );
}
public function rateVideo(videoId:String, rating:Number, token:String, devkey:String):void
{
var request:URLRequest = new URLRequest( VIDEOS_URL + '/' + videoId + '/ratings' );
request.contentType = 'application/atom+xml; charset=UTF-8';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ /* new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ), */
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ),
new URLRequestHeader( 'GData-Version', '2' ),
new URLRequestHeader( 'X-GData-Key', 'key=' + devkey ) ];
request.data = '<?xml version="1.0" encoding="UTF-8"?>' +
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005">' +
'<gd:rating value="' + rating + '" min="1" max="5"/>' +
'</entry>';
load( request );
}
public function exchangeForSessionToken(token:String):void
{
var request:URLRequest = new URLRequest( 'https://accounts.googleapis.com/accounts/AuthSubSessionToken' );
request.contentType = 'application/x-www-form-urlencoded';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ /* new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ), */
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ) ];
request.data = new URLVariables( 'foo=bar' );
load( request );
}
public function getUploadToken(token:String, devkey:String, title:String, description:String, category:String, keywords:String):void
{
var request:URLRequest = new URLRequest( GDATA_URL.replace( '/feeds/api/', '/action/GetUploadToken' ) );
request.contentType = 'application/atom+xml; charset=UTF-8';
request.method = URLRequestMethod.POST;
request.requestHeaders = [ /* new URLRequestHeader( 'X-HTTP-Method-Override', 'GET' ), */
new URLRequestHeader( 'Authorization', 'AuthSub token="' + token + '"' ),
new URLRequestHeader( 'GData-Version', '2' ),
new URLRequestHeader( 'X-GData-Key', 'key=' + devkey ) ];
request.data = '<?xml version="1.0" encoding="UTF-8"?>' +
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">' +
'<media:group><media:title type="plain">' + title + '</media:title>' +
'<media:description type="plain">' + description + '</media:description>' +
'<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">' + category + '</media:category>' +
'<media:keywords>' + keywords + '</media:keywords>' +
'</media:group></entry>';
load( request );
}
private function load(request:URLRequest):void
{
loader.load( request );
dispatchEvent( new DataServiceEvent( DataServiceEvent.LOADING ) );
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
4a54ccbb9539a463363da9b4181c621fd82f0049
|
using my string util now
|
diff --git a/com/firestartermedia/lib/as3/utils/YouTubeUtil.as b/com/firestartermedia/lib/as3/utils/YouTubeUtil.as
index ac3198f..ebd7fb3 100644
--- a/com/firestartermedia/lib/as3/utils/YouTubeUtil.as
+++ b/com/firestartermedia/lib/as3/utils/YouTubeUtil.as
@@ -1,42 +1,38 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
- //import com.adobe.utils.DateUtil;
-
- import mx.utils.StringUtil;
-
public class YouTubeUtil
{
public static function cleanGDataFeed(data:XML):Array
{
var cleanData:Array = [ ];
for each ( var entry:XML in data..*::entry )
{
- if ( mx.utils.StringUtil.trim( entry..*::videoid ) != '' )
+ if ( StringUtil.trim( entry..*::videoid ) != '' )
{
cleanData.push({
title: entry.*::title,
description: entry..*::description,
keywords: entry..*::keywords,
author: entry.*::author.name,
username: entry..*::credit.toString(),
videoId: entry..*::videoid.toString(),
rating: entry.*::rating.@average,
views: NumberUtil.format( entry.*::statistics.@viewCount ),
uploaded: DateUtil.parseW3CDTF( entry..*::uploaded.toString() ).valueOf()
});
}
}
return cleanData;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
204356b5f49ff16dbe5b9e0026584de03a228c1b
|
forgot to cast a return type, woops!
|
diff --git a/com/firestartermedia/lib/as3/utils/StringUtil.as b/com/firestartermedia/lib/as3/utils/StringUtil.as
index 64a846b..98c3a44 100644
--- a/com/firestartermedia/lib/as3/utils/StringUtil.as
+++ b/com/firestartermedia/lib/as3/utils/StringUtil.as
@@ -1,47 +1,47 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
public class StringUtil
{
public static function removeSpaces(string:String):String
{
return string.replace( /\s*/gim, '' );
}
public static function multiply(string:String, times:Number):String
{
var result:String = '';
for ( var i:Number = 0; i < times; i++ )
{
result = result + string;
}
return result;
}
public static function print(obj:*, level:Number=0):void
{
var tabs:String = StringUtil.multiply( "\t", level );
for ( var prop:String in obj )
{
trace( tabs + '[' + prop + '] -> ' + obj[ prop ] );
StringUtil.print( obj[ prop ], level + 1 );
}
}
- public static function trim(s:String):void
+ public static function trim(s:String):String
{
return s.replace( /^\s+|\s+$/gs, '' );
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
0cc7bcbeff9831731c3358f53409d8f4b3f43def
|
added trim func
|
diff --git a/com/firestartermedia/lib/as3/utils/StringUtil.as b/com/firestartermedia/lib/as3/utils/StringUtil.as
index 3f07b83..64a846b 100644
--- a/com/firestartermedia/lib/as3/utils/StringUtil.as
+++ b/com/firestartermedia/lib/as3/utils/StringUtil.as
@@ -1,42 +1,47 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
public class StringUtil
{
public static function removeSpaces(string:String):String
{
return string.replace( /\s*/gim, '' );
}
public static function multiply(string:String, times:Number):String
{
var result:String = '';
for ( var i:Number = 0; i < times; i++ )
{
result = result + string;
}
return result;
}
public static function print(obj:*, level:Number=0):void
{
var tabs:String = StringUtil.multiply( "\t", level );
for ( var prop:String in obj )
{
trace( tabs + '[' + prop + '] -> ' + obj[ prop ] );
- Â Â Â Â Â Â
+
StringUtil.print( obj[ prop ], level + 1 );
}
}
+
+ public static function trim(s:String):void
+ {
+ return s.replace( /^\s+|\s+$/gs, '' );
+ }
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
911ddb9f24fcf7f37a1c0eac4c39b68a994df6a9
|
added better auto/playing
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/VideoPlayerChromless.as b/com/firestartermedia/lib/as3/display/component/video/VideoPlayerChromless.as
index 09bba8e..29e1d66 100644
--- a/com/firestartermedia/lib/as3/display/component/video/VideoPlayerChromless.as
+++ b/com/firestartermedia/lib/as3/display/component/video/VideoPlayerChromless.as
@@ -1,351 +1,368 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.VideoPlayerEvent;
import com.firestartermedia.lib.as3.utils.ArrayUtil;
import com.firestartermedia.lib.as3.utils.NumberUtil;
+ import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.NetStatusEvent;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.clearInterval;
import flash.utils.setInterval;
import flash.utils.setTimeout;
public class VideoPlayerChromless extends Sprite
{
public var autoPlay:Boolean = true;
public var bufferTime:Number = 2;
public var loop:Boolean = false;
private var cuePoints:Array = [ ];
private var lastFiredCuePoint:Number = 0;
private var loadedBytes:Number = 0;
private var metaData:Object = { };
private var video:Video = new Video();
private var frameInterval:Number;
private var isLoaded:Boolean;
private var isOverHalfWay:Boolean;
private var isPlaying:Boolean;
private var rawHeight:Number;
private var rawWidth:Number;
private var stream:NetStream;
private var totalSize:Number;
private var videoHeight:Number;
private var videoWidth:Number;
public function VideoPlayerChromless()
{
var connection:NetConnection = new NetConnection();
connection.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
connection.connect( null );
stream = new NetStream( connection );
stream.client = { onMetaData: handleOnMetaData };
stream.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
video.smoothing = true;
video.attachNetStream( stream );
addChild( video );
}
public function play(url:String):void
{
stream.bufferTime = bufferTime;
stream.close();
stream.play( url );
+ if ( !autoPlay )
+ {
+ stream.pause();
+ }
+ else
+ {
+ isPlaying = true;
+ }
+
isLoaded = false;
isOverHalfWay = false;
- isPlaying = true;
-
//addEventListener( Event.ENTER_FRAME, handleEnterFrame );
createInterval();
}
private function createInterval():void
{
if ( !frameInterval )
{
frameInterval = setInterval( handleEnterFrame, 250 );
}
}
private function deleteInterval():void
{
clearInterval( frameInterval );
frameInterval = 0;
}
public function stop():void
{
stream.close();
isPlaying = false;
video.alpha = 0;
deleteInterval();
}
public function seekTo(seconds:Number):void
{
stream.seek( seconds );
}
public function setVolume(volume:Number):void
{
var sound:SoundTransform = new SoundTransform( volume );
stream.soundTransform = sound;
}
private function handleEnterFrame(e:Event=null):void
{
if ( !isLoaded )
{
checkLoadingStatus();
}
if ( cuePoints.length > 0 )
{
checkForCuePoints();
}
}
private function checkLoadingStatus():void
{
var progress:Object = loadingProgress;
if ( progress.total === 1 && loadedBytes === stream.bytesLoaded )
{
isLoaded = true;
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.LOADED ) );
-
- if ( !autoPlay )
- {
- pause();
- }
}
else
{
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.LOADING, progress ) );
loadedBytes = stream.bytesLoaded;
isLoaded = false;
}
}
private function checkForCuePoints():void
{
var time:Number = playingTime.current;
var checkTime:Number = Math.floor( time );
var test:Number = ArrayUtil.search( cuePoints, checkTime );
var cuePoint:Number;
if ( test > -1 )
{
cuePoint = cuePoints[ test ];
if ( cuePoint > lastFiredCuePoint )
- {
+ {
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.CUE_POINT, { point: cuePoint, halfway: false, finished: false, duration: playingTime.total } ) );
lastFiredCuePoint = cuePoint;
- }
+ }
}
if ( !isOverHalfWay && time > ( playingTime.total / 2 ) )
{
isOverHalfWay = true;
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.HALF_WAY, { point: checkTime, halfway: true, finished: false, duration: playingTime.total } ) );
}
}
public function addCuePoint(seconds:Number):void
{
cuePoints.push( seconds );
}
public function addCuePoints(points:Array):void
{
for each ( var point:Number in points )
{
addCuePoint( point );
}
}
+ public function removeCuePoints():void
+ {
+ cuePoints = [ ];
+ }
+
public function pause():void
{
stream.pause();
isPlaying = false;
deleteInterval();
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.PAUSED ) );
}
public function resume():void
{
stream.resume();
isPlaying = true;
createInterval();
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.PLAYING ) );
}
private function handleNetStatus(e:NetStatusEvent):void
{
var code:String = e.info.code;
-
+
switch ( code )
{
case 'NetStream.Play.Start':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.BUFFERING ) );
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.STARTED ) );
createInterval();
break;
case 'NetStream.Buffer.Full':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.PLAYING ) );
createInterval();
video.alpha = 1;
break;
case 'NetStream.Play.Stop':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.ENDED, { point: playingTime.total, halfway: false, finished: true } ) );
deleteInterval();
if ( loop )
{
seekTo( 0 );
resume();
}
break;
case 'NetStream.Seek.InvalidTime':
//dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.BUFFERING ) );
break;
case 'NetStream.Seek.Notify':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.BUFFERING ) );
createInterval();
break;
case 'NetStream.Play.StreamNotFound':
case 'NetStream.Play.Failed':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.FAILED ) );
deleteInterval();
break;
}
}
private function handleOnMetaData(info:Object):void
{
metaData = info;
+
+ resize( info.width, info.height );
}
public function resize(width:Number=0, height:Number=0):void
{
rawHeight = height;
rawWidth = width;
if ( metaData.hasOwnProperty( 'height') && metaData.hasOwnProperty( 'width' ) )
{
doResize( width, height );
}
else
{
video.visible = false;
setTimeout( resize, 250, width, height );
}
}
private function doResize(width:Number, height:Number):void
{
var targetHeight:Number = ( height > 0 ? height : videoHeight );
var targetWidth:Number = targetHeight * ( metaData.width / metaData.height );
if ( targetWidth > width )
{
targetWidth = ( width > 0 ? width : videoWidth );
targetHeight = targetWidth * ( metaData.height / metaData.width );
}
videoHeight = targetHeight;
videoWidth = targetWidth;
video.height = targetHeight;
video.width = targetWidth;
video.visible = true;
video.x = ( width / 2 ) - ( targetWidth / 2 );
video.y = ( height / 2 ) - ( targetHeight / 2 );
+
+ dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.RESIZED ) );
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = stream.bytesLoaded / stream.bytesTotal;
progress.bytesLoaded = stream.bytesLoaded;
progress.bytesTotal = stream.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = stream.time;
time.total = metaData.duration;
time.formatted = NumberUtil.toTimeString( Math.round( stream.time ) ) + ' / ' + NumberUtil.toTimeString( Math.round( metaData.duration ) );
return time;
}
+
+ public function get vid():Video
+ {
+ return video;
+ }
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
5cf2923f02213ac6f1dbe7e228ba5690db43e668
|
added ability to loop the sound
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index 4814bf5..ff18726 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,262 +1,268 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
+ public var loop:Boolean = false;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String=null, autoPlay:Boolean=false)
{
super( this );
this.autoPlay = autoPlay;
if ( t )
{
play( t );
}
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
private function handleSoundOpen(e:Event):void
{
if ( !autoPlay )
{
pause();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
sound.addEventListener( Event.OPEN, handleSoundOpen );
sound.load( request, context );
channel = sound.play();
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
try
{
sound.close();
}
catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
if ( channel )
{
channel.stop();
}
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel.stop();
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
+
+ if ( loop )
+ {
+ channel = sound.play( 0 );
+ }
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
b32ccd09bdd2c9dd77702710840b7a2774cfbf26
|
added ability to cue a video once the player has loaded
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/YouTubePlayerAS3.as b/com/firestartermedia/lib/as3/display/component/video/YouTubePlayerAS3.as
index d047bcf..248ed3b 100644
--- a/com/firestartermedia/lib/as3/display/component/video/YouTubePlayerAS3.as
+++ b/com/firestartermedia/lib/as3/display/component/video/YouTubePlayerAS3.as
@@ -1,331 +1,341 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.YouTubePlayerEvent;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
import flash.system.Security;
public class YouTubePlayerAS3 extends Sprite
{
public static const QUALITY_SMALL:String = 'small';
public static const QUALITY_MEDIUM:String = 'medium';
public static const QUALITY_LARGE:String = 'large';
public static const QUALITY_HD:String = 'hd720';
public static const QUALITY_DEFAULT:String = 'default';
public var autoplay:Boolean = false;
public var chromeless:Boolean = false;
public var loop:Boolean = false;
public var pars:String = '';
public var playerHeight:Number = 300;
public var playerWidth:Number = 400;
public var quality:String = QUALITY_LARGE;
private var isLoaded:Boolean = false;
private var isPlaying:Boolean = false;
private var requestURLChromed:String = 'http://www.youtube.com/v/ID?version=3';
private var requestURLChromeless:String = 'http://www.youtube.com/apiplayer?version=3';
private var player:Object;
private var videoId:String;
public function YouTubePlayerAS3()
{
Security.allowDomain( '*' );
Security.allowDomain( 'www.youtube.com' );
Security.allowDomain( 'youtube.com' );
Security.allowDomain( 's.ytimg.com' );
Security.allowDomain( 'i.ytimg.com' );
}
public function play(videoId:String):void
{
this.videoId = videoId;
if ( !isLoaded )
{
loadPlayer();
}
else
{
playVideo();
}
}
+ public function cue(videoId:String):void
+ {
+ this.videoId = videoId;
+
+ if ( isLoaded )
+ {
+ player.cueVideoById( videoId );
+ }
+ }
+
private function loadPlayer():void
{
var request:URLRequest = new URLRequest( ( chromeless ? requestURLChromeless : requestURLChromed.replace( 'ID', videoId ) ) + ( pars.indexOf( '&' ) !== 0 ? '&' : '' ) + pars );
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener( Event.INIT, handleLoaderInit );
loader.load( request );
}
private function handleLoaderInit(e:Event):void
{
var player:Object = e.target.content;
player.addEventListener( 'onReady', handlePlayerReady );
player.addEventListener( 'onStateChange', handlePlayerStateChange );
player.addEventListener( 'onPlaybackQualityChange', handlePlayerQualityChange );
player.addEventListener( 'onError', handlePlayerError );
addChild( player as DisplayObject );
}
private function handlePlayerReady(e:Event):void
{
player = e.target;
isLoaded = true;
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.READY ) );
player.setSize( playerWidth, playerHeight );
playVideo();
}
private function handlePlayerStateChange(e:Object):void
{
var state:Number = player.getPlayerState();
switch ( state )
{
case 0:
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.ENDED ) );
isPlaying = false;
if ( loop )
{
playVideo();
}
break;
case 1:
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.PLAYING ) );
isPlaying = true;
break;
case 2:
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.PAUSED ) );
isPlaying = false;
break;
case 3:
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.BUFFERING ) );
isPlaying = false;
if ( getPlaybackQuality() != quality )
{
setPlaybackQuality( quality );
}
break;
case 4:
// hmmm?
break;
case 5:
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.QUEUED ) );
isPlaying = false;
if ( getPlaybackQuality() != quality )
{
setPlaybackQuality( quality );
}
break;
default:
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.NOT_STARTED ) );
isPlaying = false;
break;
}
}
private function handlePlayerQualityChange(e:Object):void
{
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.QUALITY_CHANGED, getPlaybackQuality() ) );
}
private function handlePlayerError(e:Object):void
{
dispatchEvent( new YouTubePlayerEvent( YouTubePlayerEvent.ERROR, e ) );
}
private function playVideo():void
{
if ( isLoaded )
{
if ( !autoplay )
{
player.cueVideoById( videoId );
}
else
{
player.loadVideoById( videoId );
}
}
}
public function stop():void
{
if ( isLoaded )
{
player.stopVideo();
}
}
public function pause():void
{
if ( isLoaded )
{
player.pauseVideo();
}
}
public function resume():void
{
if ( isLoaded )
{
player.playVideo();
}
}
public function getCurrentTime():Number
{
return ( isLoaded ? player.getCurrentTime() : 0 );
}
public function getDuration():Number
{
return ( isLoaded ? player.getDuration() : 0 );
}
public function getVideoUrl():String
{
return ( isLoaded ? player.getVideoUrl() : '' );
}
public function getPlaybackQuality():String
{
return ( isLoaded ? player.getPlaybackQuality() : '' );
}
public function getVideoBytesLoaded():Number
{
return ( isLoaded ? player.getVideoBytesLoaded() : 0 );
}
public function getVideoBytesTotal():Number
{
return ( isLoaded ? player.getVideoBytesTotal() : 0 );
}
public function setPlaybackQuality(suggestedQuality:String):void
{
if ( isLoaded )
{
player.setPlaybackQuality( suggestedQuality );
}
}
public function mute():void
{
if ( isLoaded )
{
player.mute();
}
}
public function unMute():void
{
if ( isLoaded )
{
player.unMute();
}
}
public function isMuted():Boolean
{
return ( isLoaded ? player.isMuted() : false );
}
public function setVolume(value:Number):void
{
if ( isLoaded )
{
player.setVolume( value );
}
}
public function getVolume():Number
{
return ( isLoaded ? player.getVolume() : 0 );
}
public function seekTo(seconds:Number, allowSeekAhead:Boolean=true):void
{
if ( isLoaded )
{
player.seekTo( seconds, allowSeekAhead );
}
}
public function get ytPlayer():Object
{
return ( isLoaded ? player : null );
}
public function get playing():Boolean
{
return isPlaying;
}
override public function set height(value:Number):void
{
playerHeight = value;
if ( isLoaded )
{
player.setSize( playerWidth, playerHeight );
}
}
override public function set width(value:Number):void
{
playerWidth = value;
if ( isLoaded )
{
player.setSize( playerWidth, playerHeight );
}
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
6b828f042b39b54269e39859197febc864f6c6ba
|
fixed autoplaying
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index d43bfc6..5ad1a76 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,251 +1,255 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String=null, autoPlay:Boolean=false)
{
super( this );
this.autoPlay = autoPlay;
if ( t )
{
play( t );
}
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
+ else
+ {
+ pause();
+ }
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
sound.load( request, context );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
try
{
sound.close();
}
catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
if ( channel )
{
channel.stop();
}
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel.stop();
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
c26901616910c1c1aa518491ed222a63642c38e1
|
added disconnect
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/WebCam.as b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
index 2e4af13..596488e 100644
--- a/com/firestartermedia/lib/as3/display/component/video/WebCam.as
+++ b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
@@ -1,261 +1,285 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.WebCamEvent;
import com.firestartermedia.lib.as3.utils.BitmapUtil;
import com.firestartermedia.lib.as3.utils.DateUtil;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.StatusEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class WebCam extends Sprite
{
public var recordingName:String = 'Recording' + DateUtil.toNumericalTimestamp( new Date() );
private var hasBeenDenyed:Boolean = false;
private var isRecording:Boolean = false;
public var captureURL:String;
private var _reflect:Boolean;
private var bandwidth:Number;
private var camera:Camera;
private var cameraHeight:Number;
private var cameraWidth:Number;
private var connection:NetConnection;
private var microphone:Microphone;
private var quality:Number;
private var stream:NetStream;
private var video:Video;
public function WebCam(width:Number=320, height:Number=240, bandwidth:Number=0, quality:Number=90)
{
cameraHeight = height;
cameraWidth = width;
this.bandwidth = bandwidth;
this.quality = quality;
}
public function init():void
{
var index:int = 0;
for ( var i:int = 0; i < Camera.names.length; i++ )
{
if ( Camera.names[ i ] == 'USB Video Class Video' )
{
index = i;
}
}
camera = Camera.getCamera( index.toString() );
if ( camera == null )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
if ( camera.muted && hasBeenDenyed )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
camera.addEventListener( StatusEvent.STATUS, handleCameraStatus );
camera.setMode( cameraWidth, cameraHeight, 20, true );
camera.setQuality( bandwidth, quality );
microphone = Microphone.getMicrophone();
video = new Video( cameraWidth, cameraHeight );
video.smoothing = true;
video.attachCamera( camera );
addChild( video );
}
private function handleCameraStatus(e:StatusEvent):void
{
switch ( e.code )
{
case 'Camera.Muted':
hasBeenDenyed = true;
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
break;
case 'Camera.Unmuted':
dispatchEvent( new WebCamEvent( WebCamEvent.READY ) );
break;
}
}
public function captureImage():Bitmap
{
var image:Bitmap = new Bitmap( bitmapData );
return image;
}
public function captureVideo():void
{
if ( captureURL )
{
connection = new NetConnection();
connection.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTING ) );
connection.connect( captureURL );
}
else
{
throw new ArgumentError( 'You need to specify the captureURL before you start recording' );
}
}
private function handleNetStatus(e:NetStatusEvent):void
{
var name:String = e.info.code;
switch ( name )
{
case 'NetConnection.Connect.Failed':
case 'NetConnection.Connect.Rejected':
case 'NetConnection.Connect.InvalidApp':
case 'NetConnection.Connect.AppShutdown':
throw new Error( 'Can\'t connect to the application!' );
break;
case 'NetConnection.Connect.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTED ) );
startRecording();
break;
case 'NetConnection.Connect.Closed':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTION_FAILED ) );
break;
case 'NetStream.Record.NoAccess':
case 'NetStream.Record.Failed':
throw new Error( 'Can\'t record stream!' );
break;
case 'NetStream.Record.Start':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STARTED ) );
isRecording = true;
break;
case 'NetStream.Record.Stop':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STOPPED ) );
isRecording = false;
break;
case 'NetStream.Unpublish.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_FINISHED ) );
break;
}
}
private function startRecording():void
{
stream = new NetStream( connection );
stream.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
stream.attachAudio( microphone );
stream.attachCamera( camera );
stream.publish( recordingName, 'record' );
}
public function captureVideoStop():void
{
if ( isRecording )
{
stream.close();
}
else
{
throw new Error( 'Nothing\'s recording!' );
}
}
+ public function disconnect():void
+ {
+ try
+ {
+ video.attachCamera( null );
+ }
+ catch (e:*)
+ {
+ throw new Error( 'Nothing to disconnect' );
+ }
+ }
+
+ public function getStatus():Boolean
+ {
+ try
+ {
+ return !camera.muted;
+ }
+ catch (e:*)
+ {}
+
+ return false;
+ }
+
public function set reflect(b:Boolean):void
{
var matrix:Matrix = new Matrix();
_reflect = b;
if ( b )
{
matrix.translate( -cameraWidth, 0 );
matrix.scale( -1, 1 );
}
video.transform.matrix = matrix;
}
public function get bitmapData():BitmapData
{
return BitmapUtil.grab( this, new Rectangle( 0, 0, cameraWidth, cameraHeight ), true );
}
public function get recording():Boolean
{
return isRecording;
}
public function get filename():String
{
return recordingName + '.flv';
}
override public function get height():Number
{
return cameraHeight;
}
override public function get width():Number
{
return cameraWidth;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
e0cd37e07e7d02bbc84f9146e6984ddac7e7ccc6
|
removed el trace
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/VideoPlayerChromless.as b/com/firestartermedia/lib/as3/display/component/video/VideoPlayerChromless.as
index 2a4e9e7..09bba8e 100644
--- a/com/firestartermedia/lib/as3/display/component/video/VideoPlayerChromless.as
+++ b/com/firestartermedia/lib/as3/display/component/video/VideoPlayerChromless.as
@@ -1,353 +1,351 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.VideoPlayerEvent;
import com.firestartermedia.lib.as3.utils.ArrayUtil;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.NetStatusEvent;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.clearInterval;
import flash.utils.setInterval;
import flash.utils.setTimeout;
public class VideoPlayerChromless extends Sprite
{
public var autoPlay:Boolean = true;
public var bufferTime:Number = 2;
public var loop:Boolean = false;
private var cuePoints:Array = [ ];
private var lastFiredCuePoint:Number = 0;
private var loadedBytes:Number = 0;
private var metaData:Object = { };
private var video:Video = new Video();
private var frameInterval:Number;
private var isLoaded:Boolean;
private var isOverHalfWay:Boolean;
private var isPlaying:Boolean;
private var rawHeight:Number;
private var rawWidth:Number;
private var stream:NetStream;
private var totalSize:Number;
private var videoHeight:Number;
private var videoWidth:Number;
public function VideoPlayerChromless()
{
var connection:NetConnection = new NetConnection();
connection.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
connection.connect( null );
stream = new NetStream( connection );
stream.client = { onMetaData: handleOnMetaData };
stream.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
video.smoothing = true;
video.attachNetStream( stream );
addChild( video );
}
public function play(url:String):void
{
stream.bufferTime = bufferTime;
stream.close();
stream.play( url );
isLoaded = false;
isOverHalfWay = false;
isPlaying = true;
//addEventListener( Event.ENTER_FRAME, handleEnterFrame );
createInterval();
}
private function createInterval():void
{
if ( !frameInterval )
{
frameInterval = setInterval( handleEnterFrame, 250 );
}
}
private function deleteInterval():void
{
clearInterval( frameInterval );
frameInterval = 0;
}
public function stop():void
{
stream.close();
isPlaying = false;
video.alpha = 0;
deleteInterval();
}
public function seekTo(seconds:Number):void
{
stream.seek( seconds );
}
public function setVolume(volume:Number):void
{
var sound:SoundTransform = new SoundTransform( volume );
stream.soundTransform = sound;
}
private function handleEnterFrame(e:Event=null):void
{
if ( !isLoaded )
{
checkLoadingStatus();
}
if ( cuePoints.length > 0 )
{
checkForCuePoints();
}
}
private function checkLoadingStatus():void
{
var progress:Object = loadingProgress;
- trace( loadedBytes, stream.bytesLoaded );
-
if ( progress.total === 1 && loadedBytes === stream.bytesLoaded )
{
isLoaded = true;
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.LOADED ) );
if ( !autoPlay )
{
pause();
}
}
else
{
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.LOADING, progress ) );
loadedBytes = stream.bytesLoaded;
isLoaded = false;
}
}
private function checkForCuePoints():void
{
var time:Number = playingTime.current;
var checkTime:Number = Math.floor( time );
var test:Number = ArrayUtil.search( cuePoints, checkTime );
var cuePoint:Number;
if ( test > -1 )
{
cuePoint = cuePoints[ test ];
if ( cuePoint > lastFiredCuePoint )
{
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.CUE_POINT, { point: cuePoint, halfway: false, finished: false, duration: playingTime.total } ) );
lastFiredCuePoint = cuePoint;
}
}
if ( !isOverHalfWay && time > ( playingTime.total / 2 ) )
{
isOverHalfWay = true;
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.HALF_WAY, { point: checkTime, halfway: true, finished: false, duration: playingTime.total } ) );
}
}
public function addCuePoint(seconds:Number):void
{
cuePoints.push( seconds );
}
public function addCuePoints(points:Array):void
{
for each ( var point:Number in points )
{
addCuePoint( point );
}
}
public function pause():void
{
stream.pause();
isPlaying = false;
deleteInterval();
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.PAUSED ) );
}
public function resume():void
{
stream.resume();
isPlaying = true;
createInterval();
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.PLAYING ) );
}
private function handleNetStatus(e:NetStatusEvent):void
{
var code:String = e.info.code;
switch ( code )
{
case 'NetStream.Play.Start':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.BUFFERING ) );
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.STARTED ) );
createInterval();
break;
case 'NetStream.Buffer.Full':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.PLAYING ) );
createInterval();
video.alpha = 1;
break;
case 'NetStream.Play.Stop':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.ENDED, { point: playingTime.total, halfway: false, finished: true } ) );
deleteInterval();
if ( loop )
{
seekTo( 0 );
resume();
}
break;
case 'NetStream.Seek.InvalidTime':
//dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.BUFFERING ) );
break;
case 'NetStream.Seek.Notify':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.BUFFERING ) );
createInterval();
break;
case 'NetStream.Play.StreamNotFound':
case 'NetStream.Play.Failed':
dispatchEvent( new VideoPlayerEvent( VideoPlayerEvent.FAILED ) );
deleteInterval();
break;
}
}
private function handleOnMetaData(info:Object):void
{
metaData = info;
}
public function resize(width:Number=0, height:Number=0):void
{
rawHeight = height;
rawWidth = width;
if ( metaData.hasOwnProperty( 'height') && metaData.hasOwnProperty( 'width' ) )
{
doResize( width, height );
}
else
{
video.visible = false;
setTimeout( resize, 250, width, height );
}
}
private function doResize(width:Number, height:Number):void
{
var targetHeight:Number = ( height > 0 ? height : videoHeight );
var targetWidth:Number = targetHeight * ( metaData.width / metaData.height );
if ( targetWidth > width )
{
targetWidth = ( width > 0 ? width : videoWidth );
targetHeight = targetWidth * ( metaData.height / metaData.width );
}
videoHeight = targetHeight;
videoWidth = targetWidth;
video.height = targetHeight;
video.width = targetWidth;
video.visible = true;
video.x = ( width / 2 ) - ( targetWidth / 2 );
video.y = ( height / 2 ) - ( targetHeight / 2 );
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = stream.bytesLoaded / stream.bytesTotal;
progress.bytesLoaded = stream.bytesLoaded;
progress.bytesTotal = stream.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = stream.time;
time.total = metaData.duration;
time.formatted = NumberUtil.toTimeString( Math.round( stream.time ) ) + ' / ' + NumberUtil.toTimeString( Math.round( metaData.duration ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
483f5d5d41ba921dabcb7ca6fc2e708049a2bd28
|
added new event
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/WebCam.as b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
index 8495c64..2e4af13 100644
--- a/com/firestartermedia/lib/as3/display/component/video/WebCam.as
+++ b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
@@ -1,253 +1,261 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.WebCamEvent;
import com.firestartermedia.lib.as3.utils.BitmapUtil;
import com.firestartermedia.lib.as3.utils.DateUtil;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.StatusEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class WebCam extends Sprite
{
public var recordingName:String = 'Recording' + DateUtil.toNumericalTimestamp( new Date() );
private var hasBeenDenyed:Boolean = false;
private var isRecording:Boolean = false;
public var captureURL:String;
private var _reflect:Boolean;
private var bandwidth:Number;
private var camera:Camera;
private var cameraHeight:Number;
private var cameraWidth:Number;
private var connection:NetConnection;
private var microphone:Microphone;
private var quality:Number;
private var stream:NetStream;
private var video:Video;
public function WebCam(width:Number=320, height:Number=240, bandwidth:Number=0, quality:Number=90)
{
cameraHeight = height;
cameraWidth = width;
this.bandwidth = bandwidth;
this.quality = quality;
}
public function init():void
{
var index:int = 0;
for ( var i:int = 0; i < Camera.names.length; i++ )
{
if ( Camera.names[ i ] == 'USB Video Class Video' )
{
index = i;
}
}
camera = Camera.getCamera( index.toString() );
if ( camera == null )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
if ( camera.muted && hasBeenDenyed )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
camera.addEventListener( StatusEvent.STATUS, handleCameraStatus );
camera.setMode( cameraWidth, cameraHeight, 20, true );
camera.setQuality( bandwidth, quality );
microphone = Microphone.getMicrophone();
video = new Video( cameraWidth, cameraHeight );
video.smoothing = true;
video.attachCamera( camera );
addChild( video );
}
private function handleCameraStatus(e:StatusEvent):void
{
- if ( e.code == 'Camera.Muted' )
+ switch ( e.code )
{
- hasBeenDenyed = true;
+ case 'Camera.Muted':
+ hasBeenDenyed = true;
+
+ dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
- dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
+ break;
+
+ case 'Camera.Unmuted':
+ dispatchEvent( new WebCamEvent( WebCamEvent.READY ) );
+
+ break;
}
}
public function captureImage():Bitmap
{
var image:Bitmap = new Bitmap( bitmapData );
return image;
}
public function captureVideo():void
{
if ( captureURL )
{
connection = new NetConnection();
connection.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTING ) );
connection.connect( captureURL );
}
else
{
throw new ArgumentError( 'You need to specify the captureURL before you start recording' );
}
}
private function handleNetStatus(e:NetStatusEvent):void
{
var name:String = e.info.code;
switch ( name )
{
case 'NetConnection.Connect.Failed':
case 'NetConnection.Connect.Rejected':
case 'NetConnection.Connect.InvalidApp':
case 'NetConnection.Connect.AppShutdown':
throw new Error( 'Can\'t connect to the application!' );
break;
case 'NetConnection.Connect.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTED ) );
startRecording();
break;
case 'NetConnection.Connect.Closed':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTION_FAILED ) );
break;
case 'NetStream.Record.NoAccess':
case 'NetStream.Record.Failed':
throw new Error( 'Can\'t record stream!' );
break;
case 'NetStream.Record.Start':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STARTED ) );
isRecording = true;
break;
case 'NetStream.Record.Stop':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STOPPED ) );
isRecording = false;
break;
case 'NetStream.Unpublish.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_FINISHED ) );
break;
}
}
private function startRecording():void
{
stream = new NetStream( connection );
stream.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
stream.attachAudio( microphone );
stream.attachCamera( camera );
stream.publish( recordingName, 'record' );
}
public function captureVideoStop():void
{
if ( isRecording )
{
stream.close();
}
else
{
throw new Error( 'Nothing\'s recording!' );
}
}
public function set reflect(b:Boolean):void
{
var matrix:Matrix = new Matrix();
_reflect = b;
if ( b )
{
matrix.translate( -cameraWidth, 0 );
matrix.scale( -1, 1 );
}
video.transform.matrix = matrix;
}
public function get bitmapData():BitmapData
{
return BitmapUtil.grab( this, new Rectangle( 0, 0, cameraWidth, cameraHeight ), true );
}
public function get recording():Boolean
{
return isRecording;
}
public function get filename():String
{
return recordingName + '.flv';
}
override public function get height():Number
{
return cameraHeight;
}
override public function get width():Number
{
return cameraWidth;
}
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/as3/events/WebCamEvent.as b/com/firestartermedia/lib/as3/events/WebCamEvent.as
index 82631fb..43f697a 100644
--- a/com/firestartermedia/lib/as3/events/WebCamEvent.as
+++ b/com/firestartermedia/lib/as3/events/WebCamEvent.as
@@ -1,22 +1,23 @@
package com.firestartermedia.lib.as3.events
{
import flash.events.Event;
public class WebCamEvent extends Event
{
public static const NAME:String = 'WebCamEvent';
public static const CONNECTING:String = NAME + 'Connecting';
public static const CONNECTED:String = NAME + 'Connected';
public static const CONNECTION_FAILED:String = NAME + 'ConnectionFailed';
public static const NO_WEBCAM:String = NAME + 'NoWebcam';
+ public static const READY:String = NAME + 'Ready';
public static const RECORDING_STARTED:String = NAME + 'RecordingStarted';
public static const RECORDING_STOPPED:String = NAME + 'RecordingStopped';
public static const RECORDING_FINISHED:String = NAME + 'RecordingFinished';
public function WebCamEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super( type, bubbles, cancelable );
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
177d5fe6309e45bc76fa9fb8d1bc8da7dd8c51cc
|
fixed duplication of sound issue
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index ab17b21..d43bfc6 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,244 +1,251 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String=null, autoPlay:Boolean=false)
{
super( this );
this.autoPlay = autoPlay;
if ( t )
{
play( t );
}
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
sound.load( request, context );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
try
{
sound.close();
}
catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
+ if ( channel )
+ {
+ channel.stop();
+ }
+
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
+ channel.stop();
+
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
b69a524c756545fb60244c800d996c1abf2ca612
|
added autoplay into the constructor
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index 69459c1..ab17b21 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,242 +1,244 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
- public function SoundPlayer(t:String=null)
+ public function SoundPlayer(t:String=null, autoPlay:Boolean=false)
{
super( this );
+ this.autoPlay = autoPlay;
+
if ( t )
{
play( t );
}
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
sound.load( request, context );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
try
{
sound.close();
}
catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
48e9bfdde369bfc5d3882ded6d124294235861bd
|
moved listeners
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index 1fc60c8..69459c1 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,242 +1,242 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
- public function SoundPlayer(t:String='')
+ public function SoundPlayer(t:String=null)
{
super( this );
if ( t )
{
play( t );
}
-
- sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
- sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
- sound.addEventListener( Event.ID3, handleSoundDataReady );
- sound.addEventListener( Event.COMPLETE, handleSoundComplete );
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
+ sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
+ sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
+ sound.addEventListener( Event.ID3, handleSoundDataReady );
+ sound.addEventListener( Event.COMPLETE, handleSoundComplete );
+
sound.load( request, context );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
try
{
sound.close();
}
catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
79a851599a4a1213b79beb3307128d4be9c38310
|
returning the scale
|
diff --git a/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as b/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
index 557f30a..dffc4cc 100644
--- a/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
+++ b/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
@@ -1,146 +1,147 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class DisplayObjectUtil
{
public static function removeChildren(target:DisplayObjectContainer):void
{
while ( target.numChildren )
{
target.removeChildAt( target.numChildren - 1 );
}
}
public static function addChildren(target:DisplayObjectContainer, ...children):void
{
for each ( var child:DisplayObject in children )
{
target.addChild( child );
}
}
public static function getChildren(target:DisplayObjectContainer):Array
{
var children:Array = [ ];
for ( var i:Number; target.numChildren < i; i++ )
{
children.push( target.getChildAt( i ) );
}
return children;
}
public static function loadMovie(url:String, parent:DisplayObjectContainer=null, completeFunction:Function=null, applicationDomain:ApplicationDomain=null, checkPolicyFile:Boolean=false):Loader
{
var request:URLRequest = new URLRequest( url );
var context:LoaderContext = new LoaderContext( checkPolicyFile, ( applicationDomain ||= ApplicationDomain.currentDomain ) );
var loader:Loader = new Loader();
if ( parent != null )
{
parent.addChild( loader );
}
if ( completeFunction != null )
{
loader.contentLoaderInfo.addEventListener( Event.COMPLETE, completeFunction, false, 0, true );
}
try
{
loader.load( request, context );
}
catch (e:*)
{ }
return loader;
}
- public static function scale(target:DisplayObject, width:Number=0, height:Number=0):void
+ public static function scale(target:DisplayObject, width:Number=0, height:Number=0):Number
{
/*var targetHeight:Number = ( height > 0 ? height : target.height );
var targetWidth:Number = targetHeight * ( target.width / target.height );
if ( targetWidth > target.width )
{
targetWidth = ( width > 0 ? width : target.width );
targetHeight = targetWidth * ( target.height / target.width );
}
target.height = targetHeight;
target.width = targetWidth;*/
var scaleHeight:Number = height / target.height;
var scaleWidth:Number = width / target.width;
var scale:Number = ( scaleHeight <= scaleWidth ? scaleHeight : scaleWidth );
/*target.scaleX = scale;
target.scaleY = scale;*/
target.height = target.height * scale;
target.width = target.width * scale;
+ return scale;
}
public static function eachChild(target:DisplayObjectContainer, func:Function):Array
{
var funcReturn:Array = [ ];
for ( var i:Number = 0; i < target.numChildren; i++ )
{
funcReturn.push( func.apply( null, [ target.getChildAt( i ) ] ) );
}
return funcReturn;
}
public static function centerRotate(target:DisplayObject, center:Point, degrees:Number):void
{
var m:Matrix = target.transform.matrix;
m.tx -= center.x;
m.ty -= center.y;
m.rotate( NumberUtil.toRadians( degrees ) );
m.tx += center.x;
m.ty += center.y;
target.transform.matrix = m;
}
public static function changeColour(target:DisplayObject, colour:*):void
{
var trans:ColorTransform = target.transform.colorTransform;
var c:uint = ( colour is uint ? colour : NumberUtil.toUint( colour ) );
trans.color = c;
target.transform.colorTransform = trans;
}
public static function revertColour(target:DisplayObject):void
{
target.transform.colorTransform = new ColorTransform();
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
77ac2ccd5c3a1220d0e087de4a0036e29f2eaf2c
|
using weak listener
|
diff --git a/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as b/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
index bb831a4..557f30a 100644
--- a/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
+++ b/com/firestartermedia/lib/as3/utils/DisplayObjectUtil.as
@@ -1,146 +1,146 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class DisplayObjectUtil
{
public static function removeChildren(target:DisplayObjectContainer):void
{
while ( target.numChildren )
{
target.removeChildAt( target.numChildren - 1 );
}
}
public static function addChildren(target:DisplayObjectContainer, ...children):void
{
for each ( var child:DisplayObject in children )
{
target.addChild( child );
}
}
public static function getChildren(target:DisplayObjectContainer):Array
{
var children:Array = [ ];
for ( var i:Number; target.numChildren < i; i++ )
{
children.push( target.getChildAt( i ) );
}
return children;
}
public static function loadMovie(url:String, parent:DisplayObjectContainer=null, completeFunction:Function=null, applicationDomain:ApplicationDomain=null, checkPolicyFile:Boolean=false):Loader
{
var request:URLRequest = new URLRequest( url );
var context:LoaderContext = new LoaderContext( checkPolicyFile, ( applicationDomain ||= ApplicationDomain.currentDomain ) );
var loader:Loader = new Loader();
if ( parent != null )
{
parent.addChild( loader );
}
if ( completeFunction != null )
{
- loader.contentLoaderInfo.addEventListener( Event.COMPLETE, completeFunction );
+ loader.contentLoaderInfo.addEventListener( Event.COMPLETE, completeFunction, false, 0, true );
}
try
{
loader.load( request, context );
}
catch (e:*)
{ }
return loader;
}
public static function scale(target:DisplayObject, width:Number=0, height:Number=0):void
{
/*var targetHeight:Number = ( height > 0 ? height : target.height );
var targetWidth:Number = targetHeight * ( target.width / target.height );
if ( targetWidth > target.width )
{
targetWidth = ( width > 0 ? width : target.width );
targetHeight = targetWidth * ( target.height / target.width );
}
target.height = targetHeight;
target.width = targetWidth;*/
var scaleHeight:Number = height / target.height;
var scaleWidth:Number = width / target.width;
var scale:Number = ( scaleHeight <= scaleWidth ? scaleHeight : scaleWidth );
/*target.scaleX = scale;
target.scaleY = scale;*/
target.height = target.height * scale;
target.width = target.width * scale;
}
public static function eachChild(target:DisplayObjectContainer, func:Function):Array
{
var funcReturn:Array = [ ];
for ( var i:Number = 0; i < target.numChildren; i++ )
{
funcReturn.push( func.apply( null, [ target.getChildAt( i ) ] ) );
}
return funcReturn;
}
public static function centerRotate(target:DisplayObject, center:Point, degrees:Number):void
{
var m:Matrix = target.transform.matrix;
m.tx -= center.x;
m.ty -= center.y;
m.rotate( NumberUtil.toRadians( degrees ) );
m.tx += center.x;
m.ty += center.y;
target.transform.matrix = m;
}
public static function changeColour(target:DisplayObject, colour:*):void
{
var trans:ColorTransform = target.transform.colorTransform;
var c:uint = ( colour is uint ? colour : NumberUtil.toUint( colour ) );
trans.color = c;
target.transform.colorTransform = trans;
}
public static function revertColour(target:DisplayObject):void
{
target.transform.colorTransform = new ColorTransform();
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
3f11325d48ea9114bca87af89238f5f9ccd32890
|
failed
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/WebCam.as b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
index c555100..8495c64 100644
--- a/com/firestartermedia/lib/as3/display/component/video/WebCam.as
+++ b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
@@ -1,253 +1,253 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.WebCamEvent;
import com.firestartermedia.lib.as3.utils.BitmapUtil;
import com.firestartermedia.lib.as3.utils.DateUtil;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.StatusEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class WebCam extends Sprite
{
public var recordingName:String = 'Recording' + DateUtil.toNumericalTimestamp( new Date() );
private var hasBeenDenyed:Boolean = false;
private var isRecording:Boolean = false;
public var captureURL:String;
private var _reflect:Boolean;
private var bandwidth:Number;
private var camera:Camera;
private var cameraHeight:Number;
private var cameraWidth:Number;
private var connection:NetConnection;
private var microphone:Microphone;
private var quality:Number;
private var stream:NetStream;
private var video:Video;
public function WebCam(width:Number=320, height:Number=240, bandwidth:Number=0, quality:Number=90)
{
cameraHeight = height;
cameraWidth = width;
this.bandwidth = bandwidth;
this.quality = quality;
}
public function init():void
{
var index:int = 0;
for ( var i:int = 0; i < Camera.names.length; i++ )
{
if ( Camera.names[ i ] == 'USB Video Class Video' )
{
index = i;
}
}
camera = Camera.getCamera( index.toString() );
if ( camera == null )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
- if ( camera.muted || hasBeenDenyed )
+ if ( camera.muted && hasBeenDenyed )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
camera.addEventListener( StatusEvent.STATUS, handleCameraStatus );
camera.setMode( cameraWidth, cameraHeight, 20, true );
camera.setQuality( bandwidth, quality );
microphone = Microphone.getMicrophone();
video = new Video( cameraWidth, cameraHeight );
video.smoothing = true;
video.attachCamera( camera );
addChild( video );
}
private function handleCameraStatus(e:StatusEvent):void
{
if ( e.code == 'Camera.Muted' )
{
hasBeenDenyed = true;
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
}
}
public function captureImage():Bitmap
{
var image:Bitmap = new Bitmap( bitmapData );
return image;
}
public function captureVideo():void
{
if ( captureURL )
{
connection = new NetConnection();
connection.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTING ) );
connection.connect( captureURL );
}
else
{
throw new ArgumentError( 'You need to specify the captureURL before you start recording' );
}
}
private function handleNetStatus(e:NetStatusEvent):void
{
var name:String = e.info.code;
switch ( name )
{
case 'NetConnection.Connect.Failed':
case 'NetConnection.Connect.Rejected':
case 'NetConnection.Connect.InvalidApp':
case 'NetConnection.Connect.AppShutdown':
throw new Error( 'Can\'t connect to the application!' );
break;
case 'NetConnection.Connect.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTED ) );
startRecording();
break;
case 'NetConnection.Connect.Closed':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTION_FAILED ) );
break;
case 'NetStream.Record.NoAccess':
case 'NetStream.Record.Failed':
throw new Error( 'Can\'t record stream!' );
break;
case 'NetStream.Record.Start':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STARTED ) );
isRecording = true;
break;
case 'NetStream.Record.Stop':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STOPPED ) );
isRecording = false;
break;
case 'NetStream.Unpublish.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_FINISHED ) );
break;
}
}
private function startRecording():void
{
stream = new NetStream( connection );
stream.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
stream.attachAudio( microphone );
stream.attachCamera( camera );
stream.publish( recordingName, 'record' );
}
public function captureVideoStop():void
{
if ( isRecording )
{
stream.close();
}
else
{
throw new Error( 'Nothing\'s recording!' );
}
}
public function set reflect(b:Boolean):void
{
var matrix:Matrix = new Matrix();
_reflect = b;
if ( b )
{
matrix.translate( -cameraWidth, 0 );
matrix.scale( -1, 1 );
}
video.transform.matrix = matrix;
}
public function get bitmapData():BitmapData
{
return BitmapUtil.grab( this, new Rectangle( 0, 0, cameraWidth, cameraHeight ), true );
}
public function get recording():Boolean
{
return isRecording;
}
public function get filename():String
{
return recordingName + '.flv';
}
override public function get height():Number
{
return cameraHeight;
}
override public function get width():Number
{
return cameraWidth;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
1d13c2f05ce7349549dcc45084777ac3495023b2
|
added better web cam fail detection
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/WebCam.as b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
index 8495c64..c555100 100644
--- a/com/firestartermedia/lib/as3/display/component/video/WebCam.as
+++ b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
@@ -1,253 +1,253 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.WebCamEvent;
import com.firestartermedia.lib.as3.utils.BitmapUtil;
import com.firestartermedia.lib.as3.utils.DateUtil;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.StatusEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class WebCam extends Sprite
{
public var recordingName:String = 'Recording' + DateUtil.toNumericalTimestamp( new Date() );
private var hasBeenDenyed:Boolean = false;
private var isRecording:Boolean = false;
public var captureURL:String;
private var _reflect:Boolean;
private var bandwidth:Number;
private var camera:Camera;
private var cameraHeight:Number;
private var cameraWidth:Number;
private var connection:NetConnection;
private var microphone:Microphone;
private var quality:Number;
private var stream:NetStream;
private var video:Video;
public function WebCam(width:Number=320, height:Number=240, bandwidth:Number=0, quality:Number=90)
{
cameraHeight = height;
cameraWidth = width;
this.bandwidth = bandwidth;
this.quality = quality;
}
public function init():void
{
var index:int = 0;
for ( var i:int = 0; i < Camera.names.length; i++ )
{
if ( Camera.names[ i ] == 'USB Video Class Video' )
{
index = i;
}
}
camera = Camera.getCamera( index.toString() );
if ( camera == null )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
- if ( camera.muted && hasBeenDenyed )
+ if ( camera.muted || hasBeenDenyed )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
camera.addEventListener( StatusEvent.STATUS, handleCameraStatus );
camera.setMode( cameraWidth, cameraHeight, 20, true );
camera.setQuality( bandwidth, quality );
microphone = Microphone.getMicrophone();
video = new Video( cameraWidth, cameraHeight );
video.smoothing = true;
video.attachCamera( camera );
addChild( video );
}
private function handleCameraStatus(e:StatusEvent):void
{
if ( e.code == 'Camera.Muted' )
{
hasBeenDenyed = true;
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
}
}
public function captureImage():Bitmap
{
var image:Bitmap = new Bitmap( bitmapData );
return image;
}
public function captureVideo():void
{
if ( captureURL )
{
connection = new NetConnection();
connection.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTING ) );
connection.connect( captureURL );
}
else
{
throw new ArgumentError( 'You need to specify the captureURL before you start recording' );
}
}
private function handleNetStatus(e:NetStatusEvent):void
{
var name:String = e.info.code;
switch ( name )
{
case 'NetConnection.Connect.Failed':
case 'NetConnection.Connect.Rejected':
case 'NetConnection.Connect.InvalidApp':
case 'NetConnection.Connect.AppShutdown':
throw new Error( 'Can\'t connect to the application!' );
break;
case 'NetConnection.Connect.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTED ) );
startRecording();
break;
case 'NetConnection.Connect.Closed':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTION_FAILED ) );
break;
case 'NetStream.Record.NoAccess':
case 'NetStream.Record.Failed':
throw new Error( 'Can\'t record stream!' );
break;
case 'NetStream.Record.Start':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STARTED ) );
isRecording = true;
break;
case 'NetStream.Record.Stop':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STOPPED ) );
isRecording = false;
break;
case 'NetStream.Unpublish.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_FINISHED ) );
break;
}
}
private function startRecording():void
{
stream = new NetStream( connection );
stream.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
stream.attachAudio( microphone );
stream.attachCamera( camera );
stream.publish( recordingName, 'record' );
}
public function captureVideoStop():void
{
if ( isRecording )
{
stream.close();
}
else
{
throw new Error( 'Nothing\'s recording!' );
}
}
public function set reflect(b:Boolean):void
{
var matrix:Matrix = new Matrix();
_reflect = b;
if ( b )
{
matrix.translate( -cameraWidth, 0 );
matrix.scale( -1, 1 );
}
video.transform.matrix = matrix;
}
public function get bitmapData():BitmapData
{
return BitmapUtil.grab( this, new Rectangle( 0, 0, cameraWidth, cameraHeight ), true );
}
public function get recording():Boolean
{
return isRecording;
}
public function get filename():String
{
return recordingName + '.flv';
}
override public function get height():Number
{
return cameraHeight;
}
override public function get width():Number
{
return cameraWidth;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
9668ce8c977c8c01ad966dda33be01926ab8f18f
|
changed for setting of display object container
|
diff --git a/com/firestartermedia/lib/puremvc/display/Sprite.as b/com/firestartermedia/lib/puremvc/display/Sprite.as
index dcd3e03..158e856 100644
--- a/com/firestartermedia/lib/puremvc/display/Sprite.as
+++ b/com/firestartermedia/lib/puremvc/display/Sprite.as
@@ -1,125 +1,126 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.puremvc.display
{
import com.firestartermedia.lib.puremvc.events.SpriteEvent;
import flash.display.DisplayObject;
+ import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
public class Sprite extends flash.display.Sprite
{
public static const NAME:String = 'Sprite';
public var display:Boolean = true;
public var registered:Boolean = false;
public var ready:Boolean = false;
public var tweenResize:Boolean = false;
protected var tweenTime:Number = 1;
protected var readyEvent:String;
protected var resetEvent:String;
protected var stageHeight:Number;
protected var stageWidth:Number;
public function Sprite(readyEvent:String='SpriteReady', resetEvent:String='SpriteReset')
{
this.readyEvent = readyEvent;
this.resetEvent = resetEvent;
registered = true;
}
public function addChildren(...children):void
{
for each ( var child:DisplayObject in children )
{
addChild( child );
}
}
- public function removeChildren(...children):void
+ public function removeChildren(t:DisplayObjectContainer, ...children):void
{
if ( children.length )
{
for each ( var child:DisplayObject in children )
{
- removeChild( child );
+ t.removeChild( child );
}
}
else
{
- for ( var i:Number = 0; i < numChildren; i++ )
+ for ( var i:Number = 0; i < t.numChildren; i++ )
{
- removeChildAt( i );
+ t.removeChildAt( i );
}
}
}
override public function addChild(child:DisplayObject):DisplayObject
{
super.addChild( child );
handleResize();
return child;
}
override public function addChildAt(child:DisplayObject, index:int):DisplayObject
{
super.addChildAt( child, index );
handleResize();
return child;
}
protected function sendEvent(eventName:String, body:Object=null):void
{
dispatchEvent( new SpriteEvent( eventName, body, true ) );
}
protected function sendReady(eventName:String=null):void
{
if ( !ready )
{
ready = true;
sendEvent( ( eventName ? eventName : readyEvent ) );
}
}
protected function sendReset(eventName:String=null):void
{
if ( !ready )
{
ready = false;
sendEvent( ( eventName ? eventName : resetEvent ) );
}
}
public function handleReset():void
{
ready = false;
sendReset();
}
public function handleResize(e:Object=null):void
{
if ( e )
{
stageHeight = e.height;
stageWidth = e.width;
}
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
4db4e30ac8abc548ace17816d6bb4e63ec9298e9
|
fixed issue with remove children
|
diff --git a/com/firestartermedia/lib/puremvc/display/Sprite.as b/com/firestartermedia/lib/puremvc/display/Sprite.as
index cef87bc..dcd3e03 100644
--- a/com/firestartermedia/lib/puremvc/display/Sprite.as
+++ b/com/firestartermedia/lib/puremvc/display/Sprite.as
@@ -1,125 +1,125 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.puremvc.display
{
import com.firestartermedia.lib.puremvc.events.SpriteEvent;
import flash.display.DisplayObject;
import flash.display.Sprite;
public class Sprite extends flash.display.Sprite
{
public static const NAME:String = 'Sprite';
public var display:Boolean = true;
public var registered:Boolean = false;
public var ready:Boolean = false;
public var tweenResize:Boolean = false;
protected var tweenTime:Number = 1;
protected var readyEvent:String;
protected var resetEvent:String;
protected var stageHeight:Number;
protected var stageWidth:Number;
public function Sprite(readyEvent:String='SpriteReady', resetEvent:String='SpriteReset')
{
this.readyEvent = readyEvent;
this.resetEvent = resetEvent;
registered = true;
}
public function addChildren(...children):void
{
for each ( var child:DisplayObject in children )
{
addChild( child );
}
}
public function removeChildren(...children):void
{
- if ( children )
+ if ( children.length )
{
for each ( var child:DisplayObject in children )
{
removeChild( child );
}
}
else
{
for ( var i:Number = 0; i < numChildren; i++ )
{
removeChildAt( i );
}
}
}
override public function addChild(child:DisplayObject):DisplayObject
{
super.addChild( child );
handleResize();
return child;
}
override public function addChildAt(child:DisplayObject, index:int):DisplayObject
{
super.addChildAt( child, index );
handleResize();
return child;
}
protected function sendEvent(eventName:String, body:Object=null):void
{
dispatchEvent( new SpriteEvent( eventName, body, true ) );
}
protected function sendReady(eventName:String=null):void
{
if ( !ready )
{
ready = true;
sendEvent( ( eventName ? eventName : readyEvent ) );
}
}
protected function sendReset(eventName:String=null):void
{
if ( !ready )
{
ready = false;
sendEvent( ( eventName ? eventName : resetEvent ) );
}
}
public function handleReset():void
{
ready = false;
sendReset();
}
public function handleResize(e:Object=null):void
{
if ( e )
{
stageHeight = e.height;
stageWidth = e.width;
}
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
c8fc54566c707ede6ef776b3127f1ce588891f29
|
fixed the reflect issue
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/WebCam.as b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
index a98de81..8495c64 100644
--- a/com/firestartermedia/lib/as3/display/component/video/WebCam.as
+++ b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
@@ -1,247 +1,253 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.WebCamEvent;
import com.firestartermedia.lib.as3.utils.BitmapUtil;
import com.firestartermedia.lib.as3.utils.DateUtil;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.StatusEvent;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class WebCam extends Sprite
{
public var recordingName:String = 'Recording' + DateUtil.toNumericalTimestamp( new Date() );
private var hasBeenDenyed:Boolean = false;
private var isRecording:Boolean = false;
public var captureURL:String;
+ private var _reflect:Boolean;
private var bandwidth:Number;
private var camera:Camera;
private var cameraHeight:Number;
private var cameraWidth:Number;
private var connection:NetConnection;
private var microphone:Microphone;
private var quality:Number;
private var stream:NetStream;
private var video:Video;
public function WebCam(width:Number=320, height:Number=240, bandwidth:Number=0, quality:Number=90)
{
cameraHeight = height;
cameraWidth = width;
this.bandwidth = bandwidth;
this.quality = quality;
}
public function init():void
{
var index:int = 0;
for ( var i:int = 0; i < Camera.names.length; i++ )
{
if ( Camera.names[ i ] == 'USB Video Class Video' )
{
index = i;
}
}
camera = Camera.getCamera( index.toString() );
if ( camera == null )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
if ( camera.muted && hasBeenDenyed )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
camera.addEventListener( StatusEvent.STATUS, handleCameraStatus );
camera.setMode( cameraWidth, cameraHeight, 20, true );
camera.setQuality( bandwidth, quality );
microphone = Microphone.getMicrophone();
video = new Video( cameraWidth, cameraHeight );
video.smoothing = true;
video.attachCamera( camera );
addChild( video );
}
private function handleCameraStatus(e:StatusEvent):void
{
if ( e.code == 'Camera.Muted' )
{
hasBeenDenyed = true;
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
}
}
public function captureImage():Bitmap
{
var image:Bitmap = new Bitmap( bitmapData );
return image;
}
public function captureVideo():void
{
if ( captureURL )
{
connection = new NetConnection();
connection.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTING ) );
connection.connect( captureURL );
}
else
{
throw new ArgumentError( 'You need to specify the captureURL before you start recording' );
}
}
private function handleNetStatus(e:NetStatusEvent):void
{
var name:String = e.info.code;
switch ( name )
{
case 'NetConnection.Connect.Failed':
case 'NetConnection.Connect.Rejected':
case 'NetConnection.Connect.InvalidApp':
case 'NetConnection.Connect.AppShutdown':
throw new Error( 'Can\'t connect to the application!' );
break;
case 'NetConnection.Connect.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTED ) );
startRecording();
break;
case 'NetConnection.Connect.Closed':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTION_FAILED ) );
break;
case 'NetStream.Record.NoAccess':
case 'NetStream.Record.Failed':
throw new Error( 'Can\'t record stream!' );
break;
case 'NetStream.Record.Start':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STARTED ) );
isRecording = true;
break;
case 'NetStream.Record.Stop':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STOPPED ) );
isRecording = false;
break;
case 'NetStream.Unpublish.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_FINISHED ) );
break;
}
}
private function startRecording():void
{
stream = new NetStream( connection );
stream.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
stream.attachAudio( microphone );
stream.attachCamera( camera );
stream.publish( recordingName, 'record' );
}
public function captureVideoStop():void
{
if ( isRecording )
{
stream.close();
}
else
{
throw new Error( 'Nothing\'s recording!' );
}
}
public function set reflect(b:Boolean):void
{
var matrix:Matrix = new Matrix();
- matrix.translate( -cameraWidth, 0 );
- matrix.scale( -1, 1 );
+ _reflect = b;
+
+ if ( b )
+ {
+ matrix.translate( -cameraWidth, 0 );
+ matrix.scale( -1, 1 );
+ }
video.transform.matrix = matrix;
}
public function get bitmapData():BitmapData
{
- return BitmapUtil.grab( video, new Rectangle( 0, 0, cameraWidth, cameraHeight ), true );
+ return BitmapUtil.grab( this, new Rectangle( 0, 0, cameraWidth, cameraHeight ), true );
}
public function get recording():Boolean
{
return isRecording;
}
public function get filename():String
{
return recordingName + '.flv';
}
override public function get height():Number
{
return cameraHeight;
}
override public function get width():Number
{
return cameraWidth;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
5fd15d616604f16b258782fd32744c0e2b09936f
|
added reflection
|
diff --git a/com/firestartermedia/lib/as3/display/component/video/WebCam.as b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
index 4bc426c..a98de81 100644
--- a/com/firestartermedia/lib/as3/display/component/video/WebCam.as
+++ b/com/firestartermedia/lib/as3/display/component/video/WebCam.as
@@ -1,236 +1,247 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.display.component.video
{
import com.firestartermedia.lib.as3.events.WebCamEvent;
import com.firestartermedia.lib.as3.utils.BitmapUtil;
import com.firestartermedia.lib.as3.utils.DateUtil;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.StatusEvent;
+ import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class WebCam extends Sprite
{
public var recordingName:String = 'Recording' + DateUtil.toNumericalTimestamp( new Date() );
private var hasBeenDenyed:Boolean = false;
private var isRecording:Boolean = false;
public var captureURL:String;
private var bandwidth:Number;
private var camera:Camera;
private var cameraHeight:Number;
private var cameraWidth:Number;
private var connection:NetConnection;
private var microphone:Microphone;
private var quality:Number;
private var stream:NetStream;
private var video:Video;
public function WebCam(width:Number=320, height:Number=240, bandwidth:Number=0, quality:Number=90)
{
cameraHeight = height;
cameraWidth = width;
this.bandwidth = bandwidth;
this.quality = quality;
}
public function init():void
{
var index:int = 0;
for ( var i:int = 0; i < Camera.names.length; i++ )
{
if ( Camera.names[ i ] == 'USB Video Class Video' )
{
index = i;
}
}
camera = Camera.getCamera( index.toString() );
if ( camera == null )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
if ( camera.muted && hasBeenDenyed )
{
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
return;
}
camera.addEventListener( StatusEvent.STATUS, handleCameraStatus );
camera.setMode( cameraWidth, cameraHeight, 20, true );
camera.setQuality( bandwidth, quality );
microphone = Microphone.getMicrophone();
video = new Video( cameraWidth, cameraHeight );
video.smoothing = true;
video.attachCamera( camera );
addChild( video );
}
private function handleCameraStatus(e:StatusEvent):void
{
if ( e.code == 'Camera.Muted' )
{
hasBeenDenyed = true;
dispatchEvent( new WebCamEvent( WebCamEvent.NO_WEBCAM ) );
}
}
public function captureImage():Bitmap
{
var image:Bitmap = new Bitmap( bitmapData );
return image;
}
public function captureVideo():void
{
if ( captureURL )
{
connection = new NetConnection();
connection.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTING ) );
connection.connect( captureURL );
}
else
{
throw new ArgumentError( 'You need to specify the captureURL before you start recording' );
}
}
private function handleNetStatus(e:NetStatusEvent):void
{
var name:String = e.info.code;
switch ( name )
{
case 'NetConnection.Connect.Failed':
case 'NetConnection.Connect.Rejected':
case 'NetConnection.Connect.InvalidApp':
case 'NetConnection.Connect.AppShutdown':
throw new Error( 'Can\'t connect to the application!' );
break;
case 'NetConnection.Connect.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTED ) );
startRecording();
break;
case 'NetConnection.Connect.Closed':
dispatchEvent( new WebCamEvent( WebCamEvent.CONNECTION_FAILED ) );
break;
case 'NetStream.Record.NoAccess':
case 'NetStream.Record.Failed':
throw new Error( 'Can\'t record stream!' );
break;
case 'NetStream.Record.Start':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STARTED ) );
isRecording = true;
break;
case 'NetStream.Record.Stop':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_STOPPED ) );
isRecording = false;
break;
case 'NetStream.Unpublish.Success':
dispatchEvent( new WebCamEvent( WebCamEvent.RECORDING_FINISHED ) );
break;
}
}
private function startRecording():void
{
stream = new NetStream( connection );
stream.addEventListener( NetStatusEvent.NET_STATUS, handleNetStatus );
stream.attachAudio( microphone );
stream.attachCamera( camera );
stream.publish( recordingName, 'record' );
}
public function captureVideoStop():void
{
if ( isRecording )
{
stream.close();
}
else
{
throw new Error( 'Nothing\'s recording!' );
}
}
+ public function set reflect(b:Boolean):void
+ {
+ var matrix:Matrix = new Matrix();
+
+ matrix.translate( -cameraWidth, 0 );
+ matrix.scale( -1, 1 );
+
+ video.transform.matrix = matrix;
+ }
+
public function get bitmapData():BitmapData
{
return BitmapUtil.grab( video, new Rectangle( 0, 0, cameraWidth, cameraHeight ), true );
}
public function get recording():Boolean
{
return isRecording;
}
public function get filename():String
{
return recordingName + '.flv';
}
override public function get height():Number
{
return cameraHeight;
}
override public function get width():Number
{
return cameraWidth;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
cc892ce1c4b65868a938781873532cc6e28325ba
|
added fallback for adding/removing mediators
|
diff --git a/com/firestartermedia/lib/puremvc/patterns/ApplicationMediator.as b/com/firestartermedia/lib/puremvc/patterns/ApplicationMediator.as
index 56e571e..d52f35f 100644
--- a/com/firestartermedia/lib/puremvc/patterns/ApplicationMediator.as
+++ b/com/firestartermedia/lib/puremvc/patterns/ApplicationMediator.as
@@ -1,108 +1,136 @@
package com.firestartermedia.lib.puremvc.patterns
{
import com.firestartermedia.lib.as3.utils.ArrayUtil;
import flash.utils.getDefinitionByName;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.INotification;
public class ApplicationMediator extends Mediator implements IMediator
{
protected var classPath:String = 'com.firestartermedia.view.';
protected var excludedMediators:Array = [ ];
protected var tabbedMediators:Array = [ ];
protected var viewNamingHide:String = 'Hide';
protected var viewNamingMediator:String = 'Mediator';
protected var viewNamingShow:String = 'Show';
protected var currentMediator:String;
public function ApplicationMediator(name:String=null, viewComponent:Object=null)
{
super( name, viewComponent );
}
protected function addMediator(mediator:Object, data:Object=null):void
{
var m:Object;
if ( !mediator.hasOwnProperty( 'NAME' ) )
{
mediator = getDefinitionByName( classPath + mediator.toString().split( '-' )[ 0 ] ) as Class
}
if ( !facade.hasMediator( mediator.NAME ) )
{
removeOtherMediators( mediator.NAME );
facade.registerMediator( new mediator() );
m = facade.retrieveMediator( mediator.NAME );
- view.addChild( m.getViewComponent() );
+ if ( !m )
+ {
+ sendNotification( 'ApplicationFacadeFault', 'Well it looks like ' + mediator.NAME + ' hasn\'t loaded correctly' );
+
+ return;
+ }
+
+ try
+ {
+ view.addChild( m.getViewComponent() );
+ }
+ catch (e:*)
+ {
+ sendNotification( 'ApplicationFacadeFault', 'Failed to add ' + mediator.NAME + '\'s view' );
+ }
if ( m.hasOwnProperty( 'data' ) )
{
m.data = data;
}
currentMediator = mediator.NAME;
}
}
protected function removeMediator(mediator:Object):void
{
var m:Object;
if ( !mediator.hasOwnProperty( 'NAME' ) )
{
mediator = getDefinitionByName( classPath + mediator.toString().split( '-' )[ 0 ] ) as Class
}
if ( facade.hasMediator( mediator.NAME ) )
{
m = facade.retrieveMediator( mediator.NAME );
-
- view.removeChild( m.getViewComponent() );
+
+ if ( !m )
+ {
+ sendNotification( 'ApplicationFacadeFault', 'Well it looks like ' + mediator.NAME + ' hasn\'t loaded correctly' );
+
+ return;
+ }
+
+ try
+ {
+ view.removeChild( m.getViewComponent() );
+ }
+ catch (e:*)
+ {
+ sendNotification( 'ApplicationFacadeFault', 'Failed to remove ' + mediator.NAME + '\'s view' );
+ }
facade.removeMediator( mediator.NAME );
}
}
protected function removeOtherMediators(mediator:String=''):void
{
if ( ( ArrayUtil.search( excludedMediators, mediator ) === -1 && ArrayUtil.search( tabbedMediators, mediator ) !== -1 ) || mediator === '' )
{
for each ( var m:String in tabbedMediators )
{
if ( m !== mediator )
{
removeMediator( getDefinitionByName( classPath + m ) as Class );
}
}
}
}
protected function handleSectionChange(notification:INotification):void
{
var name:String = notification.getName();
var data:Object = notification.getBody();
var mediator:String = name.replace( viewNamingHide, '' ).replace( viewNamingShow, '' ) + viewNamingMediator;
if ( name.indexOf( viewNamingHide ) !== -1 )
{
removeMediator( mediator );
}
else
{
addMediator( mediator, data );
}
}
protected function mediator(name:String):*
{
return facade.retrieveMediator( name );
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
aead73f3fd6fdf94bb126837a01da1cb5327773b
|
added catch for closing the sound
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index aecea24..1fc60c8 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,238 +1,242 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String='')
{
super( this );
if ( t )
{
play( t );
}
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.load( request, context );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
- sound.close();
+ try
+ {
+ sound.close();
+ }
+ catch (e:*) {}
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
channel = sound.play( currentPosition );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel = sound.play( seconds );
channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
private function handleFinished(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
698b0401549d91e952138ea50ab2917d6c9763ff
|
added ended event
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index d977db8..aecea24 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,229 +1,238 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String='')
{
super( this );
if ( t )
{
play( t );
}
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.load( request, context );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
if ( sound.isBuffering )
{
sound.close();
}
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
channel = sound.play( currentPosition );
+ channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
+
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel = sound.play( seconds );
+ channel.addEventListener( Event.SOUND_COMPLETE, handleFinished );
+
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
+ private function handleFinished(e:Event):void
+ {
+ dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ENDED ) );
+ }
+
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
e512104bcb73b516698956bcdc53026bfaa39fd0
|
sorted out sound stopping
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index 1b33c65..d977db8 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,231 +1,229 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer(t:String='')
{
super( this );
if ( t )
{
play( t );
}
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.load( request, context );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
- sound.close();
+ if ( sound.isBuffering )
+ {
+ sound.close();
+ }
isPlaying = false;
channel = null;
}
/*else
{
throw new Error( 'There\'s nothing to stop!' );
}*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
- if ( !channel )
- {
- channel = sound.play();
- }
-
- sound.play( currentPosition );
+ channel = sound.play( currentPosition );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
/*else
{
throw new Error( 'There\'s nothing to pause!' );
}*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to mute!' );
}*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
/*else
{
throw new Error( 'There\'s nothing to unmute!' );
}*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel = sound.play( seconds );
if ( !play )
{
pause();
}
}
/*else
{
throw new Error( 'There\'s nothing to seek!' );
}*/
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
- time.current = channel.position / 1000;
+ time.current = channel ? channel.position / 1000 : 0;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/as3/utils/NumberUtil.as b/com/firestartermedia/lib/as3/utils/NumberUtil.as
index 274df72..966315d 100644
--- a/com/firestartermedia/lib/as3/utils/NumberUtil.as
+++ b/com/firestartermedia/lib/as3/utils/NumberUtil.as
@@ -1,124 +1,124 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
public class NumberUtil
{
public static function format(number:Number):String
{
var numString:String = number.toString()
var result:String = ''
var chunk:String;
while ( numString.length > 3 )
{
chunk = numString.substr( -3 );
numString = numString.substr( 0, numString.length - 3 );
result = ',' + chunk + result;
}
if ( numString.length > 0 )
{
result = numString + result;
}
return result
}
public static function toTimeString(number:Number, seperator:String=':'):String
{
var hours:Number = Math.floor( number / 3600 );
var minutes:Number = Math.floor( ( number % 3600 ) / 60 );
var seconds:Number = Math.floor( ( number % 3600 ) % 60 );
- var times:Array = [ likeTime( hours ), likeTime( minutes, true ), likeTime( seconds, true ) ];
+ var times:Array = [ likeTime( hours ), likeTime( minutes, true ), likeTime( seconds, true ) ];
var test:Function = function(item:String, index:Number, array:Array):Boolean
{
return ObjectUtil.isValid( item );
}
return times.filter( test ).join( seperator );
}
public static function likeTime(number:Number, forceZero:Boolean=false):String
{
return ( number > 0 || ( number == 0 && forceZero ) ? prependZero( number ) : '' );
}
public static function prependZero(number:Number):String
{
return ( number < 10 ? '0' + number.toString() : number.toString() );
}
public static function toUint(string:Object):uint
{
return uint( string.toString().replace( '#', '0x' ) );
}
public static function toScalar(value:Number):Number
{
return value * ( value < 0 ? -1 : 1 );
}
public static function denominate(value:Number, denominator:Number):Number
{
var actual:Number = value;
while ( actual >= denominator )
{
actual -= denominator;
}
while ( actual < -denominator )
{
actual += denominator;
}
return actual;
}
public static function actualDegrees(degrees:Number):Number
{
return denominate( degrees, 360 );
}
public static function actualRadians(radians:Number):Number
{
return denominate( radians, Math.PI * 2 );
}
public static function toDegrees(radians:Number):Number
{
return actualRadians( radians ) * ( 180 / Math.PI );
}
public static function toRadians(degrees:Number):Number
{
return actualDegrees( degrees ) * ( Math.PI / 180 );
}
public static function calculateAdjacent(value:Number, hypotenuse:Number, isAngle:Boolean=false):Number
{
var radians:Number = ( isAngle ? toRadians( value ) : actualRadians( value ) );
return Math.cos( radians ) * hypotenuse;
}
public static function calculateOppposite(value:Number, hypotenuse:Number, isAngle:Boolean=false):Number
{
var radians:Number = ( isAngle ? toRadians( value ) : actualRadians( value ) );
return Math.sin( radians ) * hypotenuse;
}
public static function calculatePartPercentage(current:Number, total:Number, loaded:Number):Number
{
return ( loaded * ( 1 / total ) * 100 ) + ( current / total ) * 100;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
26dc8b39309efdc70003236ce4256e33fc79a630
|
made some updated :)
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index 3237b17..1b33c65 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,225 +1,231 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
+ import com.firestartermedia.lib.as3.utils.NumberUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
- public var autoPlay:Boolean = true;
+ public var autoPlay:Boolean = false;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
- public function SoundPlayer()
+ public function SoundPlayer(t:String='')
{
super( this );
+ if ( t )
+ {
+ play( t );
+ }
+
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ERROR, e ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADED ) );
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = bufferTime;
currentPosition = 0;
/*if ( channel )
{
channel.stop();
channel = null;
}
if ( sound )
{
sound.close();
}*/
stop();
sound = new Sound();
sound.load( request, context );
}
public function stop():void
{
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.STOPPED ) );
channel.stop();
sound.close();
isPlaying = false;
channel = null;
}
- else
+ /*else
{
- throw new Error( 'There\'s nothing to pause!' );
- }
+ throw new Error( 'There\'s nothing to stop!' );
+ }*/
}
public function resume():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PLAYING ) );
if ( !channel )
{
channel = sound.play();
}
sound.play( currentPosition );
isPlaying = true;
}
public function pause():void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.PAUSED ) );
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
- else
+ /*else
{
throw new Error( 'There\'s nothing to pause!' );
- }
+ }*/
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.MUTED ) );
channel.soundTransform = t;
}
- else
+ /*else
{
throw new Error( 'There\'s nothing to mute!' );
- }
+ }*/
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.UNMUTED ) );
channel.soundTransform = t;
}
- else
+ /*else
{
throw new Error( 'There\'s nothing to unmute!' );
- }
+ }*/
}
public function seek(seconds:Number, play:Boolean=true):void
{
if ( sound )
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.SEEKED ) );
channel = sound.play( seconds );
if ( !play )
{
pause();
}
}
- else
+ /*else
{
- throw new Error( 'There\'s nothing to unmute!' );
- }
+ throw new Error( 'There\'s nothing to seek!' );
+ }*/
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel.position / 1000;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/as3/utils/StringUtil.as b/com/firestartermedia/lib/as3/utils/StringUtil.as
index 6911055..3f07b83 100644
--- a/com/firestartermedia/lib/as3/utils/StringUtil.as
+++ b/com/firestartermedia/lib/as3/utils/StringUtil.as
@@ -1,44 +1,42 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.utils
{
public class StringUtil
{
public static function removeSpaces(string:String):String
{
return string.replace( /\s*/gim, '' );
}
public static function multiply(string:String, times:Number):String
{
var result:String = '';
for ( var i:Number = 0; i < times; i++ )
{
- result += string;
+ result = result + string;
}
return result;
}
public static function print(obj:*, level:Number=0):void
{
- var tabs:String = '';
-
- StringUtil.multiply( "\t", level );
+ var tabs:String = StringUtil.multiply( "\t", level );
for ( var prop:String in obj )
{
trace( tabs + '[' + prop + '] -> ' + obj[ prop ] );
     Â
- print( obj[ prop ], level + 1 );
+ StringUtil.print( obj[ prop ], level + 1 );
}
}
}
}
\ No newline at end of file
diff --git a/com/firestartermedia/lib/puremvc/patterns/Facade.as b/com/firestartermedia/lib/puremvc/patterns/Facade.as
index 049a08b..d04f73b 100644
--- a/com/firestartermedia/lib/puremvc/patterns/Facade.as
+++ b/com/firestartermedia/lib/puremvc/patterns/Facade.as
@@ -1,57 +1,57 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.puremvc.patterns
{
import org.puremvc.as3.patterns.facade.Facade;
import org.puremvc.as3.patterns.observer.Notification;
public class Facade extends org.puremvc.as3.patterns.facade.Facade
{
protected var faultEvent:String;
protected var resizeEvent:String;
protected var startupEvent:String;
protected var trackEvent:String;
public function Facade(startupEvent:String, faultEvent:String, resizeEvent:String, trackEvent:String)
{
this.faultEvent = faultEvent;
this.resizeEvent = resizeEvent;
this.startupEvent = startupEvent;
this.trackEvent = trackEvent;
}
public function startup(stage:Object):void
{
sendNotification( startupEvent, stage );
}
- public function sendResize(height:Number, width:Number):void
+ public function sendResize(width:Number, height:Number):void
{
sendNotification( resizeEvent, { width: width, height: height } );
}
public function registerCommands(commands:Array, target:Class):void
{
for each ( var command:String in commands )
{
registerCommand( command, target );
}
}
override public function sendNotification(notificationName:String, body:Object=null, type:String=null):void
{
if ( notificationName !== faultEvent && notificationName !== resizeEvent && notificationName !== trackEvent )
{
sendNotification( trackEvent, { name: notificationName, body: body } );
}
notifyObservers( new Notification( notificationName, body, type ) );
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
81071c6bdf2320f143ffe82224fa715273074e7b
|
added seek and did a clean up
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index a335066..9dbe739 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,179 +1,211 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = true;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer()
{
super( this );
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.FAILED ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
- context.bufferTime = 2;
+ context.bufferTime = bufferTime;
currentPosition = 0;
- if ( channel )
+ /*if ( channel )
{
+ channel.stop();
+
channel = null;
}
if ( sound )
{
sound.close();
- }
+ }*/
+
+ stop();
sound = new Sound();
sound.load( request, context );
-
- channel = sound.play();
}
public function stop():void
{
- sound.close();
+ if ( channel )
+ {
+ channel.stop();
+
+ sound.close();
+
+ isPlaying = false;
+
+ channel = null;
+ }
+ else
+ {
+ throw new Error( 'There\'s nothing to pause!' );
+ }
}
public function resume():void
{
if ( !channel )
{
channel = sound.play();
}
sound.play( currentPosition );
isPlaying = true;
}
public function pause():void
{
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
else
{
throw new Error( 'There\'s nothing to pause!' );
}
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
channel.soundTransform = t;
}
else
{
throw new Error( 'There\'s nothing to mute!' );
}
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
channel.soundTransform = t;
}
else
{
throw new Error( 'There\'s nothing to unmute!' );
}
}
+ public function seek(seconds:Number, play:Boolean=true):void
+ {
+ if ( sound )
+ {
+ channel = sound.play( seconds );
+
+ if ( !play )
+ {
+ pause();
+ }
+ }
+ else
+ {
+ throw new Error( 'There\'s nothing to unmute!' );
+ }
+ }
+
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel.position / 1000;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
ahmednuaman/AS3
|
3ce31aea907fc279e66764b9ceecf260ccb15c7d
|
added stop
|
diff --git a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
index 2f1e72d..a335066 100644
--- a/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
+++ b/com/firestartermedia/lib/as3/sound/component/SoundPlayer.as
@@ -1,174 +1,179 @@
/**
* @author Ahmed Nuaman (http://www.ahmednuaman.com)
* @langversion 3
*
* This work is licenced under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.
* To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/uk/ or send a letter
* to Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
*/
package com.firestartermedia.lib.as3.sound.component
{
import com.firestartermedia.lib.as3.events.SoundPlayerEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
public class SoundPlayer extends EventDispatcher implements IEventDispatcher
{
public var autoPlay:Boolean = true;
public var bufferTime:Number = 2;
private var context:SoundLoaderContext = new SoundLoaderContext();
private var currentPosition:Number = 0;
private var cuePoints:Array = [ ];
private var isPlaying:Boolean = false;
private var lastFiredCuePoint:Number = 0;
private var channel:SoundChannel;
private var sound:Sound;
public function SoundPlayer()
{
super( this );
sound.addEventListener( ProgressEvent.PROGRESS, handleSoundProgress );
sound.addEventListener( IOErrorEvent.IO_ERROR, handleSoundFault );
sound.addEventListener( Event.ID3, handleSoundDataReady );
sound.addEventListener( Event.COMPLETE, handleSoundComplete );
}
private function handleSoundProgress(e:ProgressEvent):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.LOADING, loadingProgress ) );
}
private function handleSoundFault(e:*):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.FAILED ) );
}
private function handleSoundDataReady(e:Event):void
{
dispatchEvent( new SoundPlayerEvent( SoundPlayerEvent.ID3_READY, sound.id3 ) );
}
private function handleSoundComplete(e:Event):void
{
if ( autoPlay )
{
resume();
}
}
public function play(url:String):void
{
var request:URLRequest = new URLRequest( url );
context.bufferTime = 2;
currentPosition = 0;
if ( channel )
{
channel = null;
}
if ( sound )
{
sound.close();
}
sound = new Sound();
sound.load( request, context );
channel = sound.play();
}
+ public function stop():void
+ {
+ sound.close();
+ }
+
public function resume():void
{
if ( !channel )
{
channel = sound.play();
}
sound.play( currentPosition );
isPlaying = true;
}
public function pause():void
{
if ( channel )
{
currentPosition = channel.position;
channel.stop();
isPlaying = false;
}
else
{
throw new Error( 'There\'s nothing to pause!' );
}
}
public function mute():void
{
var t:SoundTransform = new SoundTransform( 0, 0 );
if ( channel )
{
channel.soundTransform = t;
}
else
{
throw new Error( 'There\'s nothing to mute!' );
}
}
public function unmute():void
{
var t:SoundTransform = new SoundTransform( 1, 0 );
if ( channel )
{
channel.soundTransform = t;
}
else
{
throw new Error( 'There\'s nothing to unmute!' );
}
}
public function get loadingProgress():Object
{
var progress:Object = { };
progress.total = sound.bytesLoaded / sound.bytesTotal;
progress.bytesLoaded = sound.bytesLoaded;
progress.bytesTotal = sound.bytesTotal;
return progress;
}
public function get playingTime():Object
{
var time:Object = { };
time.current = channel.position / 1000;
time.total = sound.length / 1000;
time.formatted = NumberUtil.toTimeString( Math.round( time.current ) ) + ' / ' + NumberUtil.toTimeString( Math.round( time.total ) );
return time;
}
}
}
\ No newline at end of file
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.