code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
// // OTPAuthBarClock.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> @interface OTPAuthBarClock : UIView - (id)initWithFrame:(CGRect)frame period:(NSTimeInterval)period; - (void)invalidate; @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthBarClock.h
Objective-C
asf20
780
// // OTPAuthURLEntryController.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPAuthURLEntryController.h" #import <MobileCoreServices/MobileCoreServices.h> #import "OTPAuthURL.h" #import "GTMNSString+URLArguments.h" #import "HOTPGenerator.h" #import "TOTPGenerator.h" #import "Decoder.h" #import "TwoDDecoderResult.h" #import "OTPScannerOverlayView.h" #import "GTMLocalizedString.h" #import "UIColor+MobileColors.h" @interface OTPAuthURLEntryController () @property(nonatomic, readwrite, assign) UITextField *activeTextField; @property(nonatomic, readwrite, assign) UIBarButtonItem *doneButtonItem; @property(nonatomic, readwrite, retain) Decoder *decoder; // queue is retained using dispatch_queue retain semantics. @property (nonatomic, retain) __attribute__((NSObject)) dispatch_queue_t queue; @property (nonatomic, retain) AVCaptureSession *avSession; @property BOOL handleCapture; - (void)keyboardWasShown:(NSNotification*)aNotification; - (void)keyboardWillBeHidden:(NSNotification*)aNotification; @end @implementation OTPAuthURLEntryController @synthesize delegate = delegate_; @synthesize doneButtonItem = doneButtonItem_; @synthesize accountName = accountName_; @synthesize accountKey = accountKey_; @synthesize accountNameLabel = accountNameLabel_; @synthesize accountKeyLabel = accountKeyLabel_; @synthesize accountType = accountType_; @synthesize scanBarcodeButton = scanBarcodeButton_; @synthesize scrollView = scrollView_; @synthesize activeTextField = activeTextField_; @synthesize decoder = decoder_; @dynamic queue; @synthesize avSession = avSession_; @synthesize handleCapture = handleCapture_; - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // On an iPad, support both portrait modes and landscape modes. return UIInterfaceOrientationIsLandscape(interfaceOrientation) || UIInterfaceOrientationIsPortrait(interfaceOrientation); } // On a phone/pod, don't support upside-down portrait. return interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationIsLandscape(interfaceOrientation); } - (void)dealloc { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self]; self.delegate = nil; self.doneButtonItem = nil; self.accountName = nil; self.accountKey = nil; self.accountNameLabel = nil; self.accountKeyLabel = nil; self.accountType = nil; self.scanBarcodeButton = nil; self.scrollView = nil; self.decoder = nil; self.queue = nil; self.avSession = nil; self.queue = nil; [super dealloc]; } - (void)viewDidLoad { self.accountName.placeholder = GTMLocalizedString(@"user@example.com", @"Placeholder string for used acccount"); self.accountNameLabel.text = GTMLocalizedString(@"Account:", @"Label for Account field"); self.accountKey.placeholder = GTMLocalizedString(@"Enter your key", @"Placeholder string for key field"); self.accountKeyLabel.text = GTMLocalizedString(@"Key:", @"Label for Key field"); [self.scanBarcodeButton setTitle:GTMLocalizedString(@"Scan Barcode", @"Scan Barcode button title") forState:UIControlStateNormal]; [self.accountType setTitle:GTMLocalizedString(@"Time Based", @"Time Based Account Type") forSegmentAtIndex:0]; [self.accountType setTitle:GTMLocalizedString(@"Counter Based", @"Counter Based Account Type") forSegmentAtIndex:1]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; [nc addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; } - (void)viewWillAppear:(BOOL)animated { self.accountName.text = @""; self.accountKey.text = @""; self.doneButtonItem = self.navigationController.navigationBar.topItem.rightBarButtonItem; self.doneButtonItem.enabled = NO; self.decoder = [[[Decoder alloc] init] autorelease]; self.decoder.delegate = self; self.scrollView.backgroundColor = [UIColor googleBlueBackgroundColor]; // Hide the Scan button if we don't have a camera that will support video. AVCaptureDevice *device = nil; if ([AVCaptureDevice class]) { // AVCaptureDevice is not supported on iOS 3.1.3 device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; } if (!device) { [self.scanBarcodeButton setHidden:YES]; } } - (void)viewWillDisappear:(BOOL)animated { self.doneButtonItem = nil; self.handleCapture = NO; [self.avSession stopRunning]; } - (dispatch_queue_t)queue { return queue_; } - (void)setQueue:(dispatch_queue_t)aQueue { if (queue_ != aQueue) { if (queue_) { dispatch_release(queue_); } queue_ = aQueue; if (queue_) { dispatch_retain(queue_); } } } // Called when the UIKeyboardDidShowNotification is sent. - (void)keyboardWasShown:(NSNotification*)aNotification { NSDictionary* info = [aNotification userInfo]; CGFloat offset = 0; // UIKeyboardFrameBeginUserInfoKey does not exist on iOS 3.1.3 if (&UIKeyboardFrameBeginUserInfoKey != NULL) { NSValue *sizeValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGSize keyboardSize = [sizeValue CGRectValue].size; BOOL isLandscape = UIInterfaceOrientationIsLandscape(self.interfaceOrientation); offset = isLandscape ? keyboardSize.width : keyboardSize.height; } else { NSValue *sizeValue = [info objectForKey:UIKeyboardBoundsUserInfoKey]; CGSize keyboardSize = [sizeValue CGRectValue].size; // The keyboard size value appears to rotate correctly on iOS 3.1.3. offset = keyboardSize.height; } UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, offset, 0.0); self.scrollView.contentInset = contentInsets; self.scrollView.scrollIndicatorInsets = contentInsets; // If active text field is hidden by keyboard, scroll it so it's visible. CGRect aRect = self.view.frame; aRect.size.height -= offset; if (self.activeTextField) { CGPoint origin = self.activeTextField.frame.origin; origin.y += CGRectGetHeight(self.activeTextField.frame); if (!CGRectContainsPoint(aRect, origin) ) { CGPoint scrollPoint = CGPointMake(0.0, - (self.activeTextField.frame.origin.y - offset)); [self.scrollView setContentOffset:scrollPoint animated:YES]; } } } - (void)keyboardWillBeHidden:(NSNotification*)aNotification { UIEdgeInsets contentInsets = UIEdgeInsetsZero; self.scrollView.contentInset = contentInsets; self.scrollView.scrollIndicatorInsets = contentInsets; } - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)orientation { // Scrolling is only enabled when in landscape. if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) { self.scrollView.contentSize = self.view.bounds.size; } else { self.scrollView.contentSize = CGSizeZero; } } #pragma mark - #pragma mark Actions - (IBAction)accountNameDidEndOnExit:(id)sender { [self.accountKey becomeFirstResponder]; } - (IBAction)accountKeyDidEndOnExit:(id)sender { [self done:sender]; } - (IBAction)done:(id)sender { // Force the keyboard away. [self.activeTextField resignFirstResponder]; NSString *encodedSecret = self.accountKey.text; NSData *secret = [OTPAuthURL base32Decode:encodedSecret]; if ([secret length]) { Class authURLClass = Nil; if ([accountType_ selectedSegmentIndex] == 0) { authURLClass = [TOTPAuthURL class]; } else { authURLClass = [HOTPAuthURL class]; } NSString *name = self.accountName.text; OTPAuthURL *authURL = [[[authURLClass alloc] initWithSecret:secret name:name] autorelease]; NSString *checkCode = authURL.checkCode; if (checkCode) { [self.delegate authURLEntryController:self didCreateAuthURL:authURL]; } } else { NSString *title = GTMLocalizedString(@"Invalid Key", @"Alert title describing a bad key"); NSString *message = nil; if ([encodedSecret length]) { message = [NSString stringWithFormat: GTMLocalizedString(@"The key '%@' is invalid.", @"Alert describing invalid key"), encodedSecret]; } else { message = GTMLocalizedString(@"You must enter a key.", @"Alert describing missing key"); } NSString *button = GTMLocalizedString(@"Try Again", @"Button title to try again"); UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:button otherButtonTitles:nil] autorelease]; [alert show]; } } - (IBAction)cancel:(id)sender { self.handleCapture = NO; [self.avSession stopRunning]; [self dismissModalViewControllerAnimated:NO]; } - (IBAction)scanBarcode:(id)sender { if (!self.avSession) { self.avSession = [[[AVCaptureSession alloc] init] autorelease]; AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil]; [self.avSession addInput:captureInput]; dispatch_queue_t queue = dispatch_queue_create("OTPAuthURLEntryController", 0); self.queue = queue; dispatch_release(queue); AVCaptureVideoDataOutput *captureOutput = [[[AVCaptureVideoDataOutput alloc] init] autorelease]; [captureOutput setAlwaysDiscardsLateVideoFrames:YES]; [captureOutput setMinFrameDuration:CMTimeMake(5,1)]; // At most 5 frames/sec. [captureOutput setSampleBufferDelegate:self queue:self.queue]; NSNumber *bgra = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA]; NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys: bgra, kCVPixelBufferPixelFormatTypeKey, nil]; [captureOutput setVideoSettings:videoSettings]; [self.avSession addOutput:captureOutput]; } AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.avSession]; [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill]; UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; NSString *cancelString = GTMLocalizedString(@"Cancel", @"Cancel button for taking pictures"); cancelButton.accessibilityLabel = @"Cancel"; CGFloat height = [UIFont systemFontSize]; CGSize size = [cancelString sizeWithFont:[UIFont systemFontOfSize:height]]; [cancelButton setTitle:cancelString forState:UIControlStateNormal]; UIViewController *previewController = [[[UIViewController alloc] init] autorelease]; [previewController.view.layer addSublayer:previewLayer]; CGRect frame = previewController.view.bounds; previewLayer.frame = frame; OTPScannerOverlayView *overlayView = [[[OTPScannerOverlayView alloc] initWithFrame:frame] autorelease]; [previewController.view addSubview:overlayView]; // Center the cancel button horizontally, and put it // kBottomPadding from the bottom of the view. static const int kBottomPadding = 10; static const int kInternalXMargin = 10; static const int kInternalYMargin = 10; frame = CGRectMake(CGRectGetMidX(frame) - ((size.width / 2) + kInternalXMargin), CGRectGetHeight(frame) - (height + (2 * kInternalYMargin) + kBottomPadding), (2 * kInternalXMargin) + size.width, height + (2 * kInternalYMargin)); [cancelButton setFrame:frame]; // Set it up so that if the view should resize, the cancel button stays // h-centered and v-bottom-fixed in the view. cancelButton.autoresizingMask = (UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin); [cancelButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside]; [overlayView addSubview:cancelButton]; [self presentModalViewController:previewController animated:NO]; self.handleCapture = YES; [self.avSession startRunning]; } - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { if (!self.handleCapture) return; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); if (imageBuffer) { CVReturn ret = CVPixelBufferLockBaseAddress(imageBuffer, 0); if (ret == kCVReturnSuccess) { uint8_t *base = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); size_t width = CVPixelBufferGetWidth(imageBuffer); size_t height = CVPixelBufferGetHeight(imageBuffer); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(base, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGImageRef cgImage = CGBitmapContextCreateImage(context); CGContextRelease(context); UIImage *image = [UIImage imageWithCGImage:cgImage]; CFRelease(cgImage); CVPixelBufferUnlockBaseAddress(imageBuffer, 0); [self.decoder performSelectorOnMainThread:@selector(decodeImage:) withObject:image waitUntilDone:NO]; } else { NSLog(@"Unable to lock buffer %d", ret); } } else { NSLog(@"Unable to get imageBuffer from %@", sampleBuffer); } [pool release]; } #pragma mark - #pragma mark UITextField Delegate Methods - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField == self.accountKey) { NSMutableString *key = [NSMutableString stringWithString:self.accountKey.text]; [key replaceCharactersInRange:range withString:string]; self.doneButtonItem.enabled = [key length] > 0; } return YES; } - (void)textFieldDidBeginEditing:(UITextField *)textField { self.activeTextField = textField; } - (void)textFieldDidEndEditing:(UITextField *)textField { self.activeTextField = nil; } #pragma mark - #pragma mark DecoderDelegate - (void)decoder:(Decoder *)decoder didDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset withResult:(TwoDDecoderResult *)twoDResult { if (self.handleCapture) { self.handleCapture = NO; NSString *urlString = twoDResult.text; NSURL *url = [NSURL URLWithString:urlString]; OTPAuthURL *authURL = [OTPAuthURL authURLWithURL:url secret:nil]; [self.avSession stopRunning]; if (authURL) { [self.delegate authURLEntryController:self didCreateAuthURL:authURL]; [self dismissModalViewControllerAnimated:NO]; } else { NSString *title = GTMLocalizedString(@"Invalid Barcode", @"Alert title describing a bad barcode"); NSString *message = [NSString stringWithFormat: GTMLocalizedString(@"The barcode '%@' is not a valid " @"authentication token barcode.", @"Alert describing invalid barcode type."), urlString]; NSString *button = GTMLocalizedString(@"Try Again", @"Button title to try again"); UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:button otherButtonTitles:nil] autorelease]; [alert show]; } } } - (void)decoder:(Decoder *)decoder failedToDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset reason:(NSString *)reason { } #pragma mark - #pragma mark UIAlertViewDelegate - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { self.handleCapture = YES; [self.avSession startRunning]; } @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthURLEntryController.m
Objective-C
asf20
17,957
// // TOTPGeneratorTest.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "TOTPGenerator.h" #import <SenTestingKit/SenTestingKit.h> @interface TOTPGeneratorTest : SenTestCase - (void)testTOTP; @end @implementation TOTPGeneratorTest // http://www.ietf.org/rfc/rfc4226.txt // Appendix B. Test Vectors // Only SHA1 defined in test vectors. - (void)testTOTP { NSString *secret = @"12345678901234567890"; NSData *secretData = [secret dataUsingEncoding:NSASCIIStringEncoding]; NSTimeInterval intervals[] = { 1111111111, 1234567890, 2000000000 }; NSArray *algorithms = [NSArray arrayWithObjects: kOTPGeneratorSHA1Algorithm, kOTPGeneratorSHA256Algorithm, kOTPGeneratorSHA512Algorithm, kOTPGeneratorSHAMD5Algorithm, nil]; NSArray *results = [NSArray arrayWithObjects: // SHA1 SHA256 SHA512 MD5 @"050471", @"584430", @"380122", @"275841", // date1 @"005924", @"829826", @"671578", @"280616", // date2 @"279037", @"428693", @"464532", @"090484", // date3 nil]; for (size_t i = 0, j = 0; i < sizeof(intervals)/sizeof(*intervals); i++) { for (NSString *algorithm in algorithms) { TOTPGenerator *generator = [[[TOTPGenerator alloc] initWithSecret:secretData algorithm:algorithm digits:6 period:30] autorelease]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:intervals[i]]; STAssertEqualObjects([results objectAtIndex:j], [generator generateOTPForDate:date], @"Invalid result %d, %@, %@", i, algorithm, date); j = j + 1; } } } @end
001coldblade-authenticator
mobile/ios/Classes/TOTPGeneratorTest.m
Objective-C
asf20
2,480
// // OTPAuthURL.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPAuthURL.h" #import <Security/Security.h> #import "GTMNSDictionary+URLArguments.h" #import "GTMNSString+URLArguments.h" #import "GTMNSScanner+Unsigned.h" #import "GTMStringEncoding.h" #import "HOTPGenerator.h" #import "TOTPGenerator.h" static NSString *const kOTPAuthScheme = @"otpauth"; static NSString *const kTOTPAuthScheme = @"totp"; static NSString *const kOTPService = @"com.google.otp.authentication"; // These are keys in the otpauth:// query string. static NSString *const kQueryAlgorithmKey = @"algorithm"; static NSString *const kQuerySecretKey = @"secret"; static NSString *const kQueryCounterKey = @"counter"; static NSString *const kQueryDigitsKey = @"digits"; static NSString *const kQueryPeriodKey = @"period"; static NSString *const kBase32Charset = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; static NSString *const kBase32Synonyms = @"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; static NSString *const kBase32Sep = @" -"; static const NSTimeInterval kTOTPDefaultSecondsBeforeChange = 5; NSString *const OTPAuthURLWillGenerateNewOTPWarningNotification = @"OTPAuthURLWillGenerateNewOTPWarningNotification"; NSString *const OTPAuthURLDidGenerateNewOTPNotification = @"OTPAuthURLDidGenerateNewOTPNotification"; NSString *const OTPAuthURLSecondsBeforeNewOTPKey = @"OTPAuthURLSecondsBeforeNewOTP"; @interface OTPAuthURL () // re-declare readwrite @property(readwrite, retain, nonatomic) NSData *keychainItemRef; @property(readwrite, retain, nonatomic) OTPGenerator *generator; // Initialize an OTPAuthURL with a dictionary of attributes from a keychain. + (OTPAuthURL *)authURLWithKeychainDictionary:(NSDictionary *)dict; // Initialize an OTPAuthURL object with an otpauth:// NSURL object. - (id)initWithOTPGenerator:(OTPGenerator *)generator name:(NSString *)name; @end @interface TOTPAuthURL () @property (nonatomic, readwrite, assign) NSTimeInterval lastProgress; @property (nonatomic, readwrite, assign) BOOL warningSent; + (void)totpTimer:(NSTimer *)timer; - (id)initWithTOTPURL:(NSURL *)url; - (id)initWithName:(NSString *)name secret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits query:(NSDictionary *)query; @end @interface HOTPAuthURL () + (BOOL)isValidCounter:(NSString *)counter; - (id)initWithName:(NSString *)name secret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits query:(NSDictionary *)query; @property(readwrite, copy, nonatomic) NSString *otpCode; @end @implementation OTPAuthURL @synthesize name = name_; @synthesize keychainItemRef = keychainItemRef_; @synthesize generator = generator_; @dynamic checkCode; @dynamic otpCode; + (OTPAuthURL *)authURLWithURL:(NSURL *)url secret:(NSData *)secret { OTPAuthURL *authURL = nil; NSString *urlScheme = [url scheme]; if ([urlScheme isEqualToString:kTOTPAuthScheme]) { // Convert totp:// into otpauth:// authURL = [[[TOTPAuthURL alloc] initWithTOTPURL:url] autorelease]; } else if (![urlScheme isEqualToString:kOTPAuthScheme]) { // Required (otpauth://) _GTMDevLog(@"invalid scheme: %@", [url scheme]); } else { NSString *path = [url path]; if ([path length] > 1) { // Optional UTF-8 encoded human readable description (skip leading "/") NSString *name = [[url path] substringFromIndex:1]; NSDictionary *query = [NSDictionary gtm_dictionaryWithHttpArgumentsString:[url query]]; // Optional algorithm=(SHA1|SHA256|SHA512|MD5) defaults to SHA1 NSString *algorithm = [query objectForKey:kQueryAlgorithmKey]; if (!algorithm) { algorithm = [OTPGenerator defaultAlgorithm]; } if (!secret) { // Required secret=Base32EncodedKey NSString *secretString = [query objectForKey:kQuerySecretKey]; secret = [OTPAuthURL base32Decode:secretString]; } // Optional digits=[68] defaults to 8 NSString *digitString = [query objectForKey:kQueryDigitsKey]; NSUInteger digits = 0; if (!digitString) { digits = [OTPGenerator defaultDigits]; } else { digits = [digitString intValue]; } NSString *type = [url host]; if ([type isEqualToString:@"hotp"]) { authURL = [[[HOTPAuthURL alloc] initWithName:name secret:secret algorithm:algorithm digits:digits query:query] autorelease]; } else if ([type isEqualToString:@"totp"]) { authURL = [[[TOTPAuthURL alloc] initWithName:name secret:secret algorithm:algorithm digits:digits query:query] autorelease]; } } } return authURL; } + (OTPAuthURL *)authURLWithKeychainItemRef:(NSData *)data { OTPAuthURL *authURL = nil; NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys: (id)kSecClassGenericPassword, kSecClass, data, (id)kSecValuePersistentRef, (id)kCFBooleanTrue, kSecReturnAttributes, (id)kCFBooleanTrue, kSecReturnData, nil]; NSDictionary *result = nil; OSStatus status = SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef*)&result); if (status == noErr) { authURL = [self authURLWithKeychainDictionary:result]; [authURL setKeychainItemRef:data]; } return authURL; } + (OTPAuthURL *)authURLWithKeychainDictionary:(NSDictionary *)dict { NSData *urlData = [dict objectForKey:(id)kSecAttrGeneric]; NSData *secretData = [dict objectForKey:(id)kSecValueData]; NSString *urlString = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] autorelease]; NSURL *url = [NSURL URLWithString:urlString]; return [self authURLWithURL:url secret:secretData]; } + (NSData *)base32Decode:(NSString *)string { GTMStringEncoding *coder = [GTMStringEncoding stringEncodingWithString:kBase32Charset]; [coder addDecodeSynonyms:kBase32Synonyms]; [coder ignoreCharacters:kBase32Sep]; return [coder decode:string]; } + (NSString *)encodeBase32:(NSData *)data { GTMStringEncoding *coder = [GTMStringEncoding stringEncodingWithString:kBase32Charset]; [coder addDecodeSynonyms:kBase32Synonyms]; [coder ignoreCharacters:kBase32Sep]; return [coder encode:data]; } - (id)initWithOTPGenerator:(OTPGenerator *)generator name:(NSString *)name { if ((self = [super init])) { if (!generator || !name) { _GTMDevLog(@"Bad Args Generator:%@ Name:%@", generator, name); [self release]; self = nil; } else { self.generator = generator; self.name = name; } } return self; } - (id)init { [self doesNotRecognizeSelector:_cmd]; return nil; } - (void)dealloc { self.generator = nil; self.name = nil; self.keychainItemRef = nil; [super dealloc]; } - (NSURL *)url { [self doesNotRecognizeSelector:_cmd]; return nil; } - (BOOL)saveToKeychain { NSString *urlString = [[self url] absoluteString]; NSData *urlData = [urlString dataUsingEncoding:NSUTF8StringEncoding]; NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:urlData forKey:(id)kSecAttrGeneric]; OSStatus status; if ([self isInKeychain]) { NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys: (id)kSecClassGenericPassword, (id)kSecClass, self.keychainItemRef, (id)kSecValuePersistentRef, nil]; status = SecItemUpdate((CFDictionaryRef)query, (CFDictionaryRef)attributes); _GTMDevLog(@"SecItemUpdate(%@, %@) = %ld", query, attributes, status); } else { [attributes setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass]; [attributes setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnPersistentRef]; [attributes setObject:self.generator.secret forKey:(id)kSecValueData]; [attributes setObject:kOTPService forKey:(id)kSecAttrService]; NSData *ref = nil; // The name here has to be unique or else we will get a errSecDuplicateItem // so if we have two items with the same name, we will just append a // random number on the end until we get success. We will try at max of // 1000 times so as to not hang in shut down. // We do not display this name to the user, so anything will do. NSString *name = self.name; for (int i = 0; i < 1000; i++) { [attributes setObject:name forKey:(id)kSecAttrAccount]; status = SecItemAdd((CFDictionaryRef)attributes, (CFTypeRef *)&ref); if (status == errSecDuplicateItem) { name = [NSString stringWithFormat:@"%@.%ld", self.name, random()]; } else { break; } } _GTMDevLog(@"SecItemAdd(%@, %@) = %ld", attributes, ref, status); if (status == noErr) { self.keychainItemRef = ref; } } return status == noErr; } - (BOOL)removeFromKeychain { if (![self isInKeychain]) { return NO; } NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys: (id)kSecClassGenericPassword, (id)kSecClass, [self keychainItemRef], (id)kSecValuePersistentRef, nil]; OSStatus status = SecItemDelete((CFDictionaryRef)query); _GTMDevLog(@"SecItemDelete(%@) = %ld", query, status); if (status == noErr) { [self setKeychainItemRef:nil]; } return status == noErr; } - (BOOL)isInKeychain { return self.keychainItemRef != nil; } - (void)generateNextOTPCode { _GTMDevLog(@"Called generateNextOTPCode on a non-HOTP generator"); } - (NSString*)checkCode { return [self.generator generateOTPForCounter:0]; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> Name: %@ ref: %p checkCode: %@", [self class], self, self.name, self.keychainItemRef, self.checkCode]; } #pragma mark - #pragma mark URL Validation @end @implementation TOTPAuthURL static NSString *const TOTPAuthURLTimerNotification = @"TOTPAuthURLTimerNotification"; @synthesize generationAdvanceWarning = generationAdvanceWarning_; @synthesize lastProgress = lastProgress_; @synthesize warningSent = warningSent_; + (void)initialize { static NSTimer *sTOTPTimer = nil; if (!sTOTPTimer) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; sTOTPTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(totpTimer:) userInfo:nil repeats:YES]; [pool drain]; } } + (void)totpTimer:(NSTimer *)timer { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc postNotificationName:TOTPAuthURLTimerNotification object:self]; } - (id)initWithOTPGenerator:(OTPGenerator *)generator name:(NSString *)name { if ((self = [super initWithOTPGenerator:generator name:name])) { [self setGenerationAdvanceWarning:kTOTPDefaultSecondsBeforeChange]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(totpTimer:) name:TOTPAuthURLTimerNotification object:nil]; } return self; } - (id)initWithSecret:(NSData *)secret name:(NSString *)name { TOTPGenerator *generator = [[[TOTPGenerator alloc] initWithSecret:secret algorithm:[TOTPGenerator defaultAlgorithm] digits:[TOTPGenerator defaultDigits] period:[TOTPGenerator defaultPeriod]] autorelease]; return [self initWithOTPGenerator:generator name:name]; } // totp:// urls are generated by the GAIA smsauthconfig page and implement // a subset of the functionality available in otpauth:// urls, so we just // translate to that internally. - (id)initWithTOTPURL:(NSURL *)url { NSMutableString *name = nil; if ([[url user] length]) { name = [NSMutableString stringWithString:[url user]]; } if ([url host]) { [name appendFormat:@"@%@", [url host]]; } NSData *secret = [OTPAuthURL base32Decode:[url fragment]]; return [self initWithSecret:secret name:name]; } - (id)initWithName:(NSString *)name secret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits query:(NSDictionary *)query { NSString *periodString = [query objectForKey:kQueryPeriodKey]; NSTimeInterval period = 0; if (periodString) { period = [periodString doubleValue]; } else { period = [TOTPGenerator defaultPeriod]; } TOTPGenerator *generator = [[[TOTPGenerator alloc] initWithSecret:secret algorithm:algorithm digits:digits period:period] autorelease]; if ((self = [self initWithOTPGenerator:generator name:name])) { self.lastProgress = period; } return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; } - (NSString *)otpCode { return [self.generator generateOTP]; } - (void)totpTimer:(NSTimer *)timer { TOTPGenerator *generator = (TOTPGenerator *)[self generator]; NSTimeInterval delta = [[NSDate date] timeIntervalSince1970]; NSTimeInterval period = [generator period]; uint64_t progress = (uint64_t)delta % (uint64_t)period; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; if (progress == 0 || progress > self.lastProgress) { [nc postNotificationName:OTPAuthURLDidGenerateNewOTPNotification object:self]; self.lastProgress = period; self.warningSent = NO; } else if (progress > period - self.generationAdvanceWarning && !self.warningSent) { NSNumber *warning = [NSNumber numberWithInt:ceil(period - progress)]; NSDictionary *userInfo = [NSDictionary dictionaryWithObject:warning forKey:OTPAuthURLSecondsBeforeNewOTPKey]; [nc postNotificationName:OTPAuthURLWillGenerateNewOTPWarningNotification object:self userInfo:userInfo]; self.warningSent = YES; } } - (NSURL *)url { NSMutableDictionary *query = [NSMutableDictionary dictionary]; TOTPGenerator *generator = (TOTPGenerator *)[self generator]; Class generatorClass = [generator class]; NSString *algorithm = [generator algorithm]; if (![algorithm isEqualToString:[generatorClass defaultAlgorithm]]) { [query setObject:algorithm forKey:kQueryAlgorithmKey]; } NSUInteger digits = [generator digits]; if (digits != [generatorClass defaultDigits]) { id val = [NSNumber numberWithUnsignedInteger:digits]; [query setObject:val forKey:kQueryDigitsKey]; } NSTimeInterval period = [generator period]; if (fpclassify(period - [generatorClass defaultPeriod]) != FP_ZERO) { id val = [NSNumber numberWithUnsignedInteger:period]; [query setObject:val forKey:kQueryPeriodKey]; } return [NSURL URLWithString:[NSString stringWithFormat:@"%@://totp/%@?%@", kOTPAuthScheme, [self.name gtm_stringByEscapingForURLArgument], [query gtm_httpArgumentsString]]]; } @end @implementation HOTPAuthURL @synthesize otpCode = otpCode_; - (id)initWithOTPGenerator:(OTPGenerator *)generator name:(NSString *)name { if ((self = [super initWithOTPGenerator:generator name:name])) { uint64_t counter = [(HOTPGenerator *)generator counter]; self.otpCode = [generator generateOTPForCounter:counter]; } return self; } - (id)initWithSecret:(NSData *)secret name:(NSString *)name { HOTPGenerator *generator = [[[HOTPGenerator alloc] initWithSecret:secret algorithm:[HOTPGenerator defaultAlgorithm] digits:[HOTPGenerator defaultDigits] counter:[HOTPGenerator defaultInitialCounter]] autorelease]; return [self initWithOTPGenerator:generator name:name]; } - (id)initWithName:(NSString *)name secret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits query:(NSDictionary *)query { NSString *counterString = [query objectForKey:kQueryCounterKey]; if ([[self class] isValidCounter:counterString]) { NSScanner *scanner = [NSScanner scannerWithString:counterString]; uint64_t counter; BOOL goodScan = [scanner gtm_scanUnsignedLongLong:&counter]; // Good scan should always be good based on the isValidCounter check above. _GTMDevAssert(goodScan, @"goodscan should be true: %c", goodScan); HOTPGenerator *generator = [[[HOTPGenerator alloc] initWithSecret:secret algorithm:algorithm digits:digits counter:counter] autorelease]; self = [self initWithOTPGenerator:generator name:name]; } else { _GTMDevLog(@"invalid counter: %@", counterString); self = [super initWithOTPGenerator:nil name:nil]; [self release]; self = nil; } return self; } - (void)dealloc { self.otpCode = nil; [super dealloc]; } - (void)generateNextOTPCode { self.otpCode = [[self generator] generateOTP]; [self saveToKeychain]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc postNotificationName:OTPAuthURLDidGenerateNewOTPNotification object:self]; } - (NSURL *)url { NSMutableDictionary *query = [NSMutableDictionary dictionary]; HOTPGenerator *generator = (HOTPGenerator *)[self generator]; Class generatorClass = [generator class]; NSString *algorithm = [generator algorithm]; if (![algorithm isEqualToString:[generatorClass defaultAlgorithm]]) { [query setObject:algorithm forKey:kQueryAlgorithmKey]; } NSUInteger digits = [generator digits]; if (digits != [generatorClass defaultDigits]) { id val = [NSNumber numberWithUnsignedInteger:digits]; [query setObject:val forKey:kQueryDigitsKey]; } uint64_t counter = [generator counter]; id val = [NSNumber numberWithUnsignedLongLong:counter]; [query setObject:val forKey:kQueryCounterKey]; return [NSURL URLWithString:[NSString stringWithFormat:@"%@://hotp/%@?%@", kOTPAuthScheme, [[self name] gtm_stringByEscapingForURLArgument], [query gtm_httpArgumentsString]]]; } + (BOOL)isValidCounter:(NSString *)counter { NSCharacterSet *nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; NSRange pos = [counter rangeOfCharacterFromSet:nonDigits]; return pos.location == NSNotFound; } @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthURL.m
Objective-C
asf20
20,247
// // OTPTableView.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPTableView.h" @implementation OTPTableView - (void)setEditing:(BOOL)editing animated:(BOOL)animate { if (editing) { if ([self.delegate respondsToSelector:@selector(otp_tableViewWillBeginEditing:)]) { [self.delegate performSelector:@selector(otp_tableViewWillBeginEditing:) withObject:self]; } } [super setEditing:editing animated:animate]; if (!editing) { if ([self.delegate respondsToSelector:@selector(otp_tableViewDidEndEditing:)]) { [self.delegate performSelector:@selector(otp_tableViewDidEndEditing:) withObject:self]; } } } @end
001coldblade-authenticator
mobile/ios/Classes/OTPTableView.m
Objective-C
asf20
1,283
// // OTPWelcomeViewController.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> @interface OTPWelcomeViewController : UIViewController @property (retain, nonatomic, readwrite) IBOutlet UITextView *welcomeText; @end
001coldblade-authenticator
mobile/ios/Classes/OTPWelcomeViewController.h
Objective-C
asf20
801
// // TOTPGenerator.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "TOTPGenerator.h" #import "GTMDefines.h" @interface TOTPGenerator () @property(assign, nonatomic, readwrite) NSTimeInterval period; @end @implementation TOTPGenerator @synthesize period = period_; + (NSTimeInterval)defaultPeriod { return 30; } - (id)initWithSecret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits period:(NSTimeInterval)period { if ((self = [super initWithSecret:secret algorithm:algorithm digits:digits])) { if (period <= 0 || period > 300) { _GTMDevLog(@"Bad Period: %f", period); [self release]; self = nil; } else { self.period = period; } } return self; } - (NSString *)generateOTP { return [self generateOTPForDate:[NSDate date]]; } - (NSString *)generateOTPForDate:(NSDate *)date { if (!date) { // If no now date specified, use the current date. date = [NSDate date]; } NSTimeInterval seconds = [date timeIntervalSince1970]; uint64_t counter = (uint64_t)(seconds / self.period); return [super generateOTPForCounter:counter]; } @end
001coldblade-authenticator
mobile/ios/Classes/TOTPGenerator.m
Objective-C
asf20
1,783
// // HOTPGenerator.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPGenerator.h" @interface HOTPGenerator : OTPGenerator // The counter, incremented on each generated OTP. @property(assign, nonatomic) uint64_t counter; + (uint64_t)defaultInitialCounter; - (id)initWithSecret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits counter:(uint64_t)counter; @end
001coldblade-authenticator
mobile/ios/Classes/HOTPGenerator.h
Objective-C
asf20
994
// // HOTPGenerator.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPGenerator.h" #import <CommonCrypto/CommonHMAC.h> #import <CommonCrypto/CommonDigest.h> #import "GTMDefines.h" static NSUInteger kPinModTable[] = { 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, }; NSString *const kOTPGeneratorSHA1Algorithm = @"SHA1"; NSString *const kOTPGeneratorSHA256Algorithm = @"SHA256"; NSString *const kOTPGeneratorSHA512Algorithm = @"SHA512"; NSString *const kOTPGeneratorSHAMD5Algorithm = @"MD5"; @interface OTPGenerator () @property (readwrite, nonatomic, copy) NSString *algorithm; @property (readwrite, nonatomic, copy) NSData *secret; @end @implementation OTPGenerator + (NSString *)defaultAlgorithm { return kOTPGeneratorSHA1Algorithm; } + (NSUInteger)defaultDigits { return 6; } @synthesize algorithm = algorithm_; @synthesize secret = secret_; @synthesize digits = digits_; - (id)init { [self doesNotRecognizeSelector:_cmd]; return nil; } - (id)initWithSecret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits { if ((self = [super init])) { algorithm_ = [algorithm copy]; secret_ = [secret copy]; digits_ = digits; BOOL goodAlgorithm = ([algorithm isEqualToString:kOTPGeneratorSHA1Algorithm] || [algorithm isEqualToString:kOTPGeneratorSHA256Algorithm] || [algorithm isEqualToString:kOTPGeneratorSHA512Algorithm] || [algorithm isEqualToString:kOTPGeneratorSHAMD5Algorithm]); if (!goodAlgorithm || digits_ > 8 || digits_ < 6 || !secret_) { _GTMDevLog(@"Bad args digits(min 6, max 8): %d secret: %@ algorithm: %@", digits_, secret_, algorithm_); [self release]; self = nil; } } return self; } - (void)dealloc { self.algorithm = nil; self.secret = nil; [super dealloc]; } // Must be overriden by subclass. - (NSString *)generateOTP { [self doesNotRecognizeSelector:_cmd]; return nil; } - (NSString *)generateOTPForCounter:(uint64_t)counter { CCHmacAlgorithm alg; NSUInteger hashLength = 0; if ([algorithm_ isEqualToString:kOTPGeneratorSHA1Algorithm]) { alg = kCCHmacAlgSHA1; hashLength = CC_SHA1_DIGEST_LENGTH; } else if ([algorithm_ isEqualToString:kOTPGeneratorSHA256Algorithm]) { alg = kCCHmacAlgSHA256; hashLength = CC_SHA256_DIGEST_LENGTH; } else if ([algorithm_ isEqualToString:kOTPGeneratorSHA512Algorithm]) { alg = kCCHmacAlgSHA512; hashLength = CC_SHA512_DIGEST_LENGTH; } else if ([algorithm_ isEqualToString:kOTPGeneratorSHAMD5Algorithm]) { alg = kCCHmacAlgMD5; hashLength = CC_MD5_DIGEST_LENGTH; } else { _GTMDevAssert(NO, @"Unknown algorithm"); return nil; } NSMutableData *hash = [NSMutableData dataWithLength:hashLength]; counter = NSSwapHostLongLongToBig(counter); NSData *counterData = [NSData dataWithBytes:&counter length:sizeof(counter)]; CCHmacContext ctx; CCHmacInit(&ctx, alg, [secret_ bytes], [secret_ length]); CCHmacUpdate(&ctx, [counterData bytes], [counterData length]); CCHmacFinal(&ctx, [hash mutableBytes]); const char *ptr = [hash bytes]; unsigned char offset = ptr[hashLength-1] & 0x0f; unsigned long truncatedHash = NSSwapBigLongToHost(*((unsigned long *)&ptr[offset])) & 0x7fffffff; unsigned long pinValue = truncatedHash % kPinModTable[digits_]; _GTMDevLog(@"secret: %@", secret_); _GTMDevLog(@"counter: %llu", counter); _GTMDevLog(@"hash: %@", hash); _GTMDevLog(@"offset: %d", offset); _GTMDevLog(@"truncatedHash: %d", truncatedHash); _GTMDevLog(@"pinValue: %d", pinValue); return [NSString stringWithFormat:@"%0*d", digits_, pinValue]; } @end
001coldblade-authenticator
mobile/ios/Classes/OTPGenerator.m
Objective-C
asf20
4,302
// // HOTPGenerator.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "HOTPGenerator.h" @implementation HOTPGenerator @synthesize counter = counter_; + (uint64_t)defaultInitialCounter { return 1; } - (id)initWithSecret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits counter:(uint64_t)counter { if ((self = [super initWithSecret:secret algorithm:algorithm digits:digits])) { counter_ = counter; } return self; } - (NSString *)generateOTP { NSUInteger counter = [self counter]; counter += 1; NSString *otp = [super generateOTPForCounter:counter]; [self setCounter:counter]; return otp; } @end
001coldblade-authenticator
mobile/ios/Classes/HOTPGenerator.m
Objective-C
asf20
1,304
// // OTPGenerator.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Foundation/Foundation.h> // The OTPGenerator class generates a one-time password (OTP) using // the HMAC-Based One-Time Password Algorithm described in RFC4226: // http://tools.ietf.org/html/rfc4226 // // The HOTP algorithm is based on an increasing counter value and a // static symmetric key known only to the token and the validation // service. In order to create the HOTP value, we will use the HMAC- // SHA-1 algorithm, as defined in RFC 2104. // // As the output of the HMAC-SHA-1 calculation is 160 bits, we must // truncate this value to something that can be easily entered by a // user. // // HOTP(K,C) = Truncate(HMAC-SHA-1(K,C)) // // Where: // // - Truncate represents the function that converts an HMAC-SHA-1 // value into an HOTP value as defined in Section 5.3 of RFC4226. // // The Key (K), the Counter (C), and Data values are hashed high-order // byte first. // // The HOTP values generated by the HOTP generator are treated as big // endian. @interface OTPGenerator : NSObject @property (readonly, nonatomic, copy) NSString *algorithm; @property (readonly, nonatomic, copy) NSData *secret; @property (readonly, nonatomic) NSUInteger digits; // Some default values. + (NSString *)defaultAlgorithm; + (NSUInteger)defaultDigits; // Designated initializer. - (id)initWithSecret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits; // Instance method to generate an OTP using the |algorithm|, |secret|, // |counter| and |digits| values configured on the object. // The return value is an NSString of |digits| length, with leading // zero-padding as required. - (NSString *)generateOTPForCounter:(uint64_t)counter; // Instance method to generate an OTP using the |algorithm|, |secret|, // |counter| and |digits| values configured on the object. // The return value is an NSString of |digits| length, with leading // zero-padding as required. - (NSString *)generateOTP; @end extern NSString *const kOTPGeneratorSHA1Algorithm; extern NSString *const kOTPGeneratorSHA256Algorithm; extern NSString *const kOTPGeneratorSHA512Algorithm; extern NSString *const kOTPGeneratorSHAMD5Algorithm;
001coldblade-authenticator
mobile/ios/Classes/OTPGenerator.h
Objective-C
asf20
2,794
// // OTPAuthAppDelegate.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPAuthAppDelegate.h" #import "GTMDefines.h" #import "OTPAuthURL.h" #import "HOTPGenerator.h" #import "TOTPGenerator.h" #import "OTPTableViewCell.h" #import "OTPAuthAboutController.h" #import "OTPWelcomeViewController.h" #import "OTPAuthBarClock.h" #import "UIColor+MobileColors.h" #import "GTMLocalizedString.h" static NSString *const kOTPKeychainEntriesArray = @"OTPKeychainEntries"; @interface OTPGoodTokenSheet : UIActionSheet @property(readwrite, nonatomic, retain) OTPAuthURL *authURL; @end @interface OTPAuthAppDelegate () // The OTPAuthURL objects in this array are loaded from the keychain at // startup and serialized there on shutdown. @property (nonatomic, retain) NSMutableArray *authURLs; @property (nonatomic, assign) RootViewController *rootViewController; @property (nonatomic, assign) UIBarButtonItem *editButton; @property (nonatomic, assign) OTPEditingState editingState; @property (nonatomic, retain) OTPAuthURL *urlBeingAdded; @property (nonatomic, retain) UIAlertView *urlAddAlert; - (void)saveKeychainArray; - (void)updateUI; - (void)updateEditing:(UITableView *)tableview; @end @implementation OTPAuthAppDelegate @synthesize window = window_; @synthesize authURLEntryController = authURLEntryController_; @synthesize navigationController = navigationController_; @synthesize authURLs = authURLs_; @synthesize rootViewController = rootViewController_; @synthesize editButton = editButton_; @synthesize editingState = editingState_; @synthesize urlAddAlert = urlAddAlert_; @synthesize authURLEntryNavigationItem = authURLEntryNavigationItem_; @synthesize legalButton = legalButton_; @synthesize navigationItem = navigationItem_; @synthesize urlBeingAdded = urlBeingAdded_; - (void)dealloc { self.window = nil; self.authURLEntryController = nil; self.navigationController = nil; self.rootViewController = nil; self.authURLs = nil; self.editButton = nil; self.urlBeingAdded = nil; self.legalButton = nil; self.navigationItem = nil; self.urlAddAlert = nil; self.authURLEntryNavigationItem = nil; [super dealloc]; } - (void)awakeFromNib { self.legalButton.title = GTMLocalizedString(@"Legal Information", @"Legal Information Button Title"); self.navigationItem.title = GTMLocalizedString(@"Google Authenticator", @"Product Name"); self.authURLEntryNavigationItem.title = GTMLocalizedString(@"Add Token", @"Add Token Navigation Screen Title"); } - (void)updateEditing:(UITableView *)tableView { if ([self.authURLs count] == 0 && [tableView isEditing]) { [tableView setEditing:NO animated:YES]; } } - (void)updateUI { BOOL hidden = YES; for (OTPAuthURL *url in self.authURLs) { if ([url isMemberOfClass:[TOTPAuthURL class]]) { hidden = NO; break; } } self.rootViewController.clock.hidden = hidden; self.editButton.enabled = [self.authURLs count] > 0; } - (void)saveKeychainArray { NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; NSArray *keychainReferences = [self valueForKeyPath:@"authURLs.keychainItemRef"]; [ud setObject:keychainReferences forKey:kOTPKeychainEntriesArray]; [ud synchronize]; } #pragma mark - #pragma mark Application Delegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; NSArray *savedKeychainReferences = [ud arrayForKey:kOTPKeychainEntriesArray]; self.authURLs = [NSMutableArray arrayWithCapacity:[savedKeychainReferences count]]; for (NSData *keychainRef in savedKeychainReferences) { OTPAuthURL *authURL = [OTPAuthURL authURLWithKeychainItemRef:keychainRef]; if (authURL) { [self.authURLs addObject:authURL]; } } self.rootViewController = (RootViewController*)[self.navigationController topViewController]; [self.window addSubview:self.navigationController.view]; if ([self.authURLs count] == 0) { OTPWelcomeViewController *controller = [[[OTPWelcomeViewController alloc] init] autorelease]; [self.navigationController pushViewController:controller animated:NO]; } [self.window makeKeyAndVisible]; return YES; } - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { OTPAuthURL *authURL = [OTPAuthURL authURLWithURL:url secret:nil]; if (authURL) { NSString *title = GTMLocalizedString(@"Add Token", @"Add Token Alert Title"); NSString *message = [NSString stringWithFormat: GTMLocalizedString(@"Do you want to add the token named “%@”?", @"Add Token Message"), [authURL name]]; NSString *noButton = GTMLocalizedString(@"No", @"No"); NSString *yesButton = GTMLocalizedString(@"Yes", @"Yes"); self.urlAddAlert = [[[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:noButton otherButtonTitles:yesButton, nil] autorelease]; self.urlBeingAdded = authURL; [self.urlAddAlert show]; } return authURL != nil; } #pragma mark - #pragma mark OTPManualAuthURLEntryControllerDelegate - (void)authURLEntryController:(OTPAuthURLEntryController*)controller didCreateAuthURL:(OTPAuthURL *)authURL { [self.navigationController dismissModalViewControllerAnimated:YES]; [self.navigationController popToRootViewControllerAnimated:NO]; [authURL saveToKeychain]; [self.authURLs addObject:authURL]; [self saveKeychainArray]; [self updateUI]; UITableView *tableView = (UITableView*)self.rootViewController.view; [tableView reloadData]; } #pragma mark - #pragma mark UINavigationControllerDelegate - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { [self.rootViewController setEditing:NO animated:animated]; // Only display the toolbar for the rootViewController. BOOL hidden = viewController != self.rootViewController; [navigationController setToolbarHidden:hidden animated:YES]; } - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated { if (viewController == self.rootViewController) { self.editButton = viewController.editButtonItem; UIToolbar *toolbar = self.navigationController.toolbar; NSMutableArray *items = [NSMutableArray arrayWithArray:toolbar.items]; // We are replacing our "proxy edit button" with a real one. [items replaceObjectAtIndex:0 withObject:self.editButton]; toolbar.items = items; [self updateUI]; } } #pragma mark - #pragma mark UITableViewDataSource - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *cellIdentifier = nil; Class cellClass = Nil; // See otp_tableViewWillBeginEditing for comments on why this is being done. NSUInteger idx = self.editingState == kOTPEditingTable ? [indexPath row] : [indexPath section]; OTPAuthURL *url = [self.authURLs objectAtIndex:idx]; if ([url isMemberOfClass:[HOTPAuthURL class]]) { cellIdentifier = @"HOTPCell"; cellClass = [HOTPTableViewCell class]; } else if ([url isMemberOfClass:[TOTPAuthURL class]]) { cellIdentifier = @"TOTPCell"; cellClass = [TOTPTableViewCell class]; } UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[[cellClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; } [(OTPTableViewCell *)cell setAuthURL:url]; return cell; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // See otp_tableViewWillBeginEditing for comments on why this is being done. return self.editingState == kOTPEditingTable ? 1 : [self.authURLs count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // See otp_tableViewWillBeginEditing for comments on why this is being done. return self.editingState == kOTPEditingTable ? [self.authURLs count] : 1; } - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { NSUInteger oldIndex = [fromIndexPath row]; NSUInteger newIndex = [toIndexPath row]; [self.authURLs exchangeObjectAtIndex:oldIndex withObjectAtIndex:newIndex]; [self saveKeychainArray]; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { OTPTableViewCell *cell = (OTPTableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; [cell didEndEditing]; [tableView beginUpdates]; NSUInteger idx = self.editingState == kOTPEditingTable ? [indexPath row] : [indexPath section]; OTPAuthURL *authURL = [self.authURLs objectAtIndex:idx]; // See otp_tableViewWillBeginEditing for comments on why this is being done. if (self.editingState == kOTPEditingTable) { NSIndexPath *path = [NSIndexPath indexPathForRow:idx inSection:0]; NSArray *rows = [NSArray arrayWithObject:path]; [tableView deleteRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationFade]; } else { NSIndexSet *set = [NSIndexSet indexSetWithIndex:idx]; [tableView deleteSections:set withRowAnimation:UITableViewRowAnimationFade]; } [authURL removeFromKeychain]; [self.authURLs removeObjectAtIndex:idx]; [self saveKeychainArray]; [tableView endUpdates]; [self updateUI]; if ([self.authURLs count] == 0 && self.editingState != kOTPEditingSingleRow) { [self.editButton.target performSelector:self.editButton.action withObject:self]; } } } #pragma mark - #pragma mark UITableViewDelegate - (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath { _GTMDevAssert(self.editingState == kOTPNotEditing, @"Should not be editing"); OTPTableViewCell *cell = (OTPTableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; [cell willBeginEditing]; self.editingState = kOTPEditingSingleRow; } - (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath { _GTMDevAssert(self.editingState == kOTPEditingSingleRow, @"Must be editing single row"); OTPTableViewCell *cell = (OTPTableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; [cell didEndEditing]; self.editingState = kOTPNotEditing; } #pragma mark - #pragma mark OTPTableViewDelegate // With iOS <= 4 there doesn't appear to be a way to move rows around safely // in a multisectional table where you want to maintain a single row per // section. You have control over where a row would go into a section with // tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath: // but it doesn't allow you to enforce only one row per section. // By doing this we collapse the table into a single section with multiple rows // when editing, and then expand back to the "spaced" out view when editing is // done. We only want this to be done when editing the entire table (by hitting // the edit button) as when you swipe a row to edit it doesn't allow you // to move the row. // When a row is swiped, tableView:willBeginEditingRowAtIndexPath: is called // first, which means that self.editingState will be set to kOTPEditingSingleRow // This means that in all code that deals with indexes of items that we need // to check to see if self.editingState == kOTPEditingTable to know whether to // check for the index of rows in section 0, or the indexes of the sections // themselves. - (void)otp_tableViewWillBeginEditing:(UITableView *)tableView { if (self.editingState == kOTPNotEditing) { self.editingState = kOTPEditingTable; [tableView reloadData]; } } - (void)otp_tableViewDidEndEditing:(UITableView *)tableView { if (self.editingState == kOTPEditingTable) { self.editingState = kOTPNotEditing; [tableView reloadData]; } } #pragma mark - #pragma mark UIAlertViewDelegate - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { _GTMDevAssert(alertView == self.urlAddAlert, @"Unexpected Alert"); if (buttonIndex == 1) { [self authURLEntryController:nil didCreateAuthURL:self.urlBeingAdded]; } self.urlBeingAdded = nil; self.urlAddAlert = nil; } #pragma mark - #pragma mark Actions -(IBAction)addAuthURL:(id)sender { [self.navigationController popToRootViewControllerAnimated:NO]; [self.rootViewController setEditing:NO animated:NO]; [self.navigationController presentModalViewController:self.authURLEntryController animated:YES]; } - (IBAction)showLegalInformation:(id)sender { OTPAuthAboutController *controller = [[[OTPAuthAboutController alloc] init] autorelease]; [self.navigationController pushViewController:controller animated:YES]; } @end #pragma mark - @implementation OTPGoodTokenSheet @synthesize authURL = authURL_; - (void)dealloc { self.authURL = nil; [super dealloc]; } @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthAppDelegate.m
Objective-C
asf20
14,280
// // OTPAuthApplication.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> @interface OTPAuthApplication : UIApplication - (IBAction)addAuthURL:(id)sender; @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthApplication.h
Objective-C
asf20
744
// // OTPWelcomeViewController.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPWelcomeViewController.h" #import "GTMLocalizedString.h" #import "OTPAuthAppDelegate.h" @implementation OTPWelcomeViewController @synthesize welcomeText = welcomeText_; - (id)init { if ((self = [super initWithNibName:@"OTPWelcomeViewController" bundle:nil])) { self.hidesBottomBarWhenPushed = YES; } return self; } - (void)dealloc { self.welcomeText = nil; [super dealloc]; } - (void)viewWillAppear:(BOOL)animated { UINavigationItem *navItem = [self navigationItem]; NSString *title = GTMLocalizedString(@"Welcome", @"Title for welcome screen"); navItem.title = title; navItem.hidesBackButton = YES; UIBarButtonItem *button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:@selector(addAuthURL:)] autorelease]; [navItem setRightBarButtonItem:button animated:NO]; NSString *label = GTMLocalizedString(@"Welcome_label", @"Welcome text"); welcomeText_.text = label; } @end
001coldblade-authenticator
mobile/ios/Classes/OTPWelcomeViewController.m
Objective-C
asf20
1,722
// // OTPAuthAppDelegate.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "RootViewController.h" #import "OTPAuthURLEntryController.h" typedef enum { kOTPNotEditing, kOTPEditingSingleRow, kOTPEditingTable } OTPEditingState; @interface OTPAuthAppDelegate : NSObject <UIApplicationDelegate, OTPAuthURLEntryControllerDelegate, UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate, UIAlertViewDelegate> @property(nonatomic, retain) IBOutlet UINavigationController *navigationController; @property(nonatomic, retain) IBOutlet UIWindow *window; @property(nonatomic, retain) IBOutlet UINavigationController *authURLEntryController; @property(nonatomic, retain) IBOutlet UIBarButtonItem *legalButton; @property(nonatomic, retain) IBOutlet UINavigationItem *navigationItem; @property(nonatomic, retain) IBOutlet UINavigationItem *authURLEntryNavigationItem; - (IBAction)addAuthURL:(id)sender; - (IBAction)showLegalInformation:(id)sender; @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthAppDelegate.h
Objective-C
asf20
1,546
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Legal Notices</title> </head> <body> <p>Authenticator &copy; 2010 Google Inc.</p> <hr /> <p><a href="http://code.google.com/p/zxing/">ZXing</a> Copyright ZXing authors</p> <p></p> <p>Licensed under the Apache License, Version 2.0 (the "License"). You may obtain a copy of the License at</p> <p></p> <p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> <hr /> <p><a href="http://code.google.com/p/google-toolbox-for-mac/">Google Toolbox For Mac</a> Copyright Google Inc.</p> <p></p> <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at</p> <p></p> <p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p> <p></p> <p>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p> </body> </html>
001coldblade-authenticator
mobile/ios/Resources/English.lproj/LegalNotices.html
HTML
asf20
1,663
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta content="text/html; charset=UTF-8" http-equiv="content-type"><title>Barcode Hints</title> <style type="text/css"> </style> <meta name="viewport" content="width=device-width; initial-scale=1.0"> </head> <body style="background-color: #EBEFF9; color: #335599; font-family: sans-serif;"> <p>The iPhone camera has a fixed focus depth which is not ideal for scanning barcodes. Anything that is too close to the camera will look fuzzy and may be difficult to decode. For best results: </p> <ul> <li>Take the picture from a distance of at least 2 feet / 60 cm.</li> <li>Use the <span style="font-style: italic;">Scale and Move</span> features to make the barcode as large and clear as possible.</li> </ul> </body> </html>
001coldblade-authenticator
mobile/ios/Resources/Hints.html
HTML
asf20
845
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.imageCache; import org.ttrssreader.R; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.Utils; import org.ttrssreader.utils.WakeLocker; import android.app.Notification; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class ForegroundService extends Service implements ICacheEndListener { protected static final String TAG = ForegroundService.class.getSimpleName(); public static final String ACTION_LOAD_IMAGES = "load_images"; public static final String ACTION_LOAD_ARTICLES = "load_articles"; public static final String PARAM_SHOW_NOTIFICATION = "show_notification"; private ImageCacher imageCacher; private static volatile ForegroundService instance = null; private static ICacheEndListener parent; public static boolean isInstanceCreated() { return instance != null; } private boolean imageCache = false; public static void loadImagesToo() { if (instance != null) instance.imageCache = true; } public static void registerCallback(ICacheEndListener parentGUI) { parent = parentGUI; } @Override public void onCreate() { instance = this; super.onCreate(); } /** * Cleans up all running notifications, notifies waiting activities and clears the instance of the service. */ public void finishService() { if (instance != null) { stopForeground(true); instance = null; } if (parent != null) parent.onCacheEnd(); } @Override public void onCacheEnd() { WakeLocker.release(); // Start a new cacher if images have been requested if (imageCache) { imageCache = false; imageCacher = new ImageCacher(this, this, false); imageCacher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { finishService(); this.stopSelf(); } } @Override public void onCacheProgress(int taskCount, int progress) { if (parent != null) parent.onCacheProgress(taskCount, progress); } @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null && intent.getAction() != null) { CharSequence title = ""; if (ACTION_LOAD_IMAGES.equals(intent.getAction())) { title = getText(R.string.Cache_service_imagecache); imageCacher = new ImageCacher(this, this, false); imageCacher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); Log.i(TAG, "Caching images started"); } else if (ACTION_LOAD_ARTICLES.equals(intent.getAction())) { title = getText(R.string.Cache_service_articlecache); imageCacher = new ImageCacher(this, this, true); imageCacher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); Log.i(TAG, "Caching (articles only) started"); } WakeLocker.acquire(this); if (intent.getBooleanExtra(PARAM_SHOW_NOTIFICATION, false)) { int icon = R.drawable.notification_icon; CharSequence ticker = getText(R.string.Cache_service_started); CharSequence text = getText(R.string.Cache_service_text); Notification notification = Utils .buildNotification(this, icon, ticker, title, text, true, new Intent()); startForeground(R.string.Cache_service_started, notification); } } return START_STICKY; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/imageCache/ForegroundService.java
Java
gpl3
4,667
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * <http://www.apache.org/licenses/LICENSE-2.0> * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package org.ttrssreader.imageCache; import org.ttrssreader.controllers.Controller; import org.ttrssreader.imageCache.bundle.BundleScrubber; import org.ttrssreader.imageCache.bundle.PluginBundleManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; /** * This is the "fire" BroadcastReceiver for a Locale Plug-in setting. * * @see com.twofortyfouram.locale.Intent#ACTION_FIRE_SETTING * @see com.twofortyfouram.locale.Intent#EXTRA_BUNDLE */ public final class PluginReceiver extends BroadcastReceiver { protected static final String TAG = PluginReceiver.class.getSimpleName(); public static final String ACTION_FIRE_SETTING = "com.twofortyfouram.locale.intent.action.FIRE_SETTING"; public static final String EXTRA_BUNDLE = "com.twofortyfouram.locale.intent.extra.BUNDLE"; /** * @param context * {@inheritDoc}. * @param intent * the incoming {@link com.twofortyfouram.locale.Intent#ACTION_FIRE_SETTING} Intent. This * should contain the {@link com.twofortyfouram.locale.Intent#EXTRA_BUNDLE} that was saved by * {@link EditActivity} and later broadcast by Locale. */ @Override public void onReceive(final Context context, final Intent intent) { /* * Always be strict on input parameters! A malicious third-party app could send a malformed Intent. */ if (!ACTION_FIRE_SETTING.equals(intent.getAction())) { Log.e(TAG, "Received unexpected Intent action " + intent.getAction()); return; } BundleScrubber.scrub(intent); final Bundle bundle = intent.getBundleExtra(EXTRA_BUNDLE); BundleScrubber.scrub(bundle); if (!PluginBundleManager.isBundleValid(bundle)) { Log.e(TAG, "Received invalid Bundle for action " + intent.getAction()); return; } Controller.getInstance().setHeadless(true); final boolean images = bundle.getBoolean(PluginBundleManager.BUNDLE_EXTRA_IMAGES); final boolean notification = bundle.getBoolean(PluginBundleManager.BUNDLE_EXTRA_NOTIFICATION); Intent serviceIntent; if (images) { serviceIntent = new Intent(ForegroundService.ACTION_LOAD_IMAGES); } else { serviceIntent = new Intent(ForegroundService.ACTION_LOAD_ARTICLES); } serviceIntent.setClass(context, ForegroundService.class); serviceIntent.putExtra(ForegroundService.PARAM_SHOW_NOTIFICATION, notification); context.startService(serviceIntent); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/imageCache/PluginReceiver.java
Java
gpl3
3,458
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * <http://www.apache.org/licenses/LICENSE-2.0> * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package org.ttrssreader.imageCache.bundle; import android.content.Intent; import android.os.Bundle; /** * Helper class to scrub Bundles of invalid extras. This is a workaround for an Android bug: * <http://code.google.com/p/android/issues/detail?id=16006>. */ public final class BundleScrubber { /** * Scrubs Intents for private serializable subclasses in the Intent extras. If the Intent's extras contain * a private serializable subclass, the Bundle is cleared. The Bundle will not be set to null. If the * Bundle is null, has no extras, or the extras do not contain a private serializable subclass, the Bundle * is not mutated. * * @param intent * {@code Intent} to scrub. This parameter may be mutated if scrubbing is necessary. This * parameter may be null. * @return true if the Intent was scrubbed, false if the Intent was not modified. */ public static boolean scrub(final Intent intent) { if (null == intent) { return false; } return scrub(intent.getExtras()); } /** * Scrubs Bundles for private serializable subclasses in the extras. If the Bundle's extras contain a * private serializable subclass, the Bundle is cleared. If the Bundle is null, has no extras, or the * extras do not contain a private serializable subclass, the Bundle is not mutated. * * @param bundle * {@code Bundle} to scrub. This parameter may be mutated if scrubbing is necessary. This * parameter may be null. * @return true if the Bundle was scrubbed, false if the Bundle was not modified. */ public static boolean scrub(final Bundle bundle) { if (null == bundle) { return false; } /* * Note: This is a hack to work around a private serializable classloader attack */ try { // if a private serializable exists, this will throw an exception bundle.containsKey(null); } catch (final Exception e) { bundle.clear(); return true; } return false; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/imageCache/bundle/BundleScrubber.java
Java
gpl3
2,906
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * <http://www.apache.org/licenses/LICENSE-2.0> * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package org.ttrssreader.imageCache.bundle; import org.ttrssreader.utils.Utils; import android.content.Context; import android.os.Bundle; import android.util.Log; /** * Class for managing the {@link com.twofortyfouram.locale.Intent#EXTRA_BUNDLE} for this plug-in. */ public final class PluginBundleManager { protected static final String TAG = PluginBundleManager.class.getSimpleName(); /** * Type: {@code String}. * <p> * String message to display in a Toast message. */ public static final String BUNDLE_EXTRA_IMAGES = "org.ttrssreader.FETCH_IMAGES"; //$NON-NLS-1$ public static final String BUNDLE_EXTRA_NOTIFICATION = "org.ttrssreader.SHOW_NOTIFICATION"; //$NON-NLS-1$ /** * Type: {@code int}. * <p> * versionCode of the plug-in that saved the Bundle. */ /* * This extra is not strictly required, however it makes backward and forward compatibility significantly * easier. For example, suppose a bug is found in how some version of the plug-in stored its Bundle. By * having the version, the plug-in can better detect when such bugs occur. */ public static final String BUNDLE_EXTRA_INT_VERSION_CODE = "org.ttrssreader.INT_VERSION_CODE"; //$NON-NLS-1$ /** * Method to verify the content of the bundle are correct. * <p> * This method will not mutate {@code bundle}. * * @param bundle * bundle to verify. May be null, which will always return false. * @return true if the Bundle is valid, false if the bundle is invalid. */ public static boolean isBundleValid(final Bundle bundle) { if (null == bundle) { return false; } /* * Make sure the expected extras exist */ if (!bundle.containsKey(BUNDLE_EXTRA_IMAGES)) { Log.e(TAG, String.format("bundle must contain extra %s", BUNDLE_EXTRA_IMAGES)); //$NON-NLS-1$ return false; } if (!bundle.containsKey(BUNDLE_EXTRA_NOTIFICATION)) { Log.e(TAG, String.format("bundle must contain extra %s", BUNDLE_EXTRA_NOTIFICATION)); //$NON-NLS-1$ return false; } if (!bundle.containsKey(BUNDLE_EXTRA_INT_VERSION_CODE)) { Log.e(TAG, String.format("bundle must contain extra %s", BUNDLE_EXTRA_INT_VERSION_CODE)); //$NON-NLS-1$ return false; } /* * Make sure the correct number of extras exist. Run this test after checking for specific Bundle * extras above so that the error message is more useful. (E.g. the caller will see what extras are * missing, rather than just a message that there is the wrong number). */ if (3 != bundle.keySet().size()) { Log.e(TAG, String.format( "bundle must contain 3 keys, but currently contains %d keys: %s", bundle.keySet().size(), bundle.keySet())); //$NON-NLS-1$ return false; } if (bundle.getInt(BUNDLE_EXTRA_INT_VERSION_CODE, 0) != bundle.getInt(BUNDLE_EXTRA_INT_VERSION_CODE, 1)) { Log.e(TAG, String.format( "bundle extra %s appears to be the wrong type. It must be an int", BUNDLE_EXTRA_INT_VERSION_CODE)); //$NON-NLS-1$ return false; } return true; } /** * @param context * Application context. * @param message * The toast message to be displayed by the plug-in. Cannot be null. * @return A plug-in bundle. */ public static Bundle generateBundle(final Context context, final boolean fetchImages, final boolean showNotification) { final Bundle result = new Bundle(); result.putInt(BUNDLE_EXTRA_INT_VERSION_CODE, Utils.getAppVersionCode(context)); result.putBoolean(BUNDLE_EXTRA_IMAGES, fetchImages); result.putBoolean(BUNDLE_EXTRA_NOTIFICATION, showNotification); return result; } /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException * because this class cannot be instantiated. */ private PluginBundleManager() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } }
025003b-rss
ttrss-reader/src/org/ttrssreader/imageCache/bundle/PluginBundleManager.java
Java
gpl3
5,089
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.imageCache; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.AbstractCache; import android.graphics.Bitmap; import android.os.Environment; import android.util.Log; /** * Implements a cache capable of caching image files. It exposes helper methods to immediately * access binary image data as {@link Bitmap} objects. * * @author Matthias Kaeppler * @author Nils Braden (modified some stuff) */ public class ImageCache extends AbstractCache<String, byte[]> { protected static final String TAG = ImageCache.class.getSimpleName(); public ImageCache(int initialCapacity, String cacheDir) { super("ImageCache", initialCapacity, 1); this.diskCacheDir = cacheDir; } /** * Enable caching to the phone's SD card. * * @param context * the current context * @return */ public boolean enableDiskCache() { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // Use configured output directory File folder = new File(diskCacheDir); if (!folder.exists()) { if (!folder.mkdirs()) { // Folder could not be created, fallback to internal directory on sdcard // Path: /sdcard/Android/data/org.ttrssreader/cache/ diskCacheDir = Constants.CACHE_FOLDER_DEFAULT; folder = new File(diskCacheDir); } } if (!folder.exists()) folder.mkdirs(); isDiskCacheEnabled = folder.exists(); // Create .nomedia File in Cache-Folder so android doesn't generate thumbnails File nomediaFile = new File(diskCacheDir + File.separator + ".nomedia"); if (!nomediaFile.exists()) { try { nomediaFile.createNewFile(); } catch (IOException e) { } } } if (!isDiskCacheEnabled) Log.e(TAG, "Failed creating disk cache directory " + diskCacheDir); return isDiskCacheEnabled; } public void fillMemoryCacheFromDisk() { byte[] b = new byte[] {}; File folder = new File(diskCacheDir); File[] files = folder.listFiles(); Log.d(TAG, "Image cache before fillMemoryCacheFromDisk: " + cache.size()); if (files == null) return; for (File file : files) { try { cache.put(file.getName(), b); } catch (RuntimeException e) { Log.e(TAG, "Runtime Exception while doing fillMemoryCacheFromDisk: " + e.getMessage()); } } Log.d(TAG, "Image cache after fillMemoryCacheFromDisk: " + cache.size()); } public boolean containsKey(String key) { return cache.containsKey(getFileNameForKey(key)) || (isDiskCacheEnabled && getCacheFile((String) key).exists()); } /** * create uniq string from file url, which can be used as file name * * @param imageUrl * URL of given image * * @return calculated hash */ public static String getHashForKey(String imageUrl) { return imageUrl.replaceAll("[:;#~%$\"!<>|+*\\()^/,%?&=]+", "+"); } @Override public String getFileNameForKey(String imageUrl) { return getHashForKey(imageUrl); } public File getCacheFile(String key) { File f = new File(diskCacheDir); if (!f.exists()) f.mkdirs(); return getFileForKey(key); } @Override protected byte[] readValueFromDisk(File file) throws IOException { return null; } @Override protected void writeValueToDisk(BufferedOutputStream ostream, byte[] value) throws IOException { } }
025003b-rss
ttrss-reader/src/org/ttrssreader/imageCache/ImageCache.java
Java
gpl3
4,759
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.imageCache; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.pojos.RemoteFile; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.annotation.SuppressLint; import android.content.Context; import android.net.ConnectivityManager; import android.os.Handler; import android.os.Looper; import android.util.Log; public class ImageCacher extends AsyncTask<Void, Integer, Void> { protected static final String TAG = ImageCacher.class.getSimpleName(); private static final int DEFAULT_TASK_COUNT = 6; private static volatile int progressImageDownload; private ICacheEndListener parent; private Context context; private boolean onlyArticles; private long cacheSizeMax; private ImageCache imageCache; private long folderSize; private long downloaded = 0; private int taskCount = 0; private long start; private Map<Integer, DownloadImageTask> map; public ImageCacher(ICacheEndListener parent, Context context, boolean onlyArticles) { this.parent = parent; this.context = context; this.onlyArticles = onlyArticles; // Create Handler in a new Thread so all tasks are started in this new thread instead of the main UI-Thread myHandler = new MyHandler(); myHandler.start(); } private static Thread myHandler; private static Handler handler; private static final Object lock = new Object(); private static volatile Boolean handlerInitialized = false; private static class MyHandler extends Thread { // Source: http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/ @Override public void run() { try { Looper.prepare(); handler = new Handler(); synchronized (lock) { handlerInitialized = true; lock.notifyAll(); } Looper.loop(); } catch (Throwable t) { t.printStackTrace(); } } }; // This method is allowed to be called from any thread public synchronized void requestStop() { // Wait for the handler to be fully initialized: long wait = Utils.SECOND * 2; if (!handlerInitialized) { synchronized (lock) { while (!handlerInitialized && wait > 0) { try { wait = wait - 300; lock.wait(300); } catch (InterruptedException e) { } } } } handler.post(new Runnable() { @Override public void run() { Looper.myLooper().quit(); } }); } @Override protected Void doInBackground(Void... params) { start = System.currentTimeMillis(); while (true) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (!Utils.checkConnected(cm)) { Log.e(TAG, "No connectivity, aborting..."); break; } // Update all articles long timeArticles = System.currentTimeMillis(); // sync local status changes to server Data.getInstance().synchronizeStatus(); // Only use progress-updates and callbacks for downloading articles, images are done in background // completely Set<Feed> labels = DBHelper.getInstance().getFeeds(-2); taskCount = DEFAULT_TASK_COUNT + labels.size(); int progress = 0; publishProgress(++progress); // Data.getInstance().updateCounters(true, true); publishProgress(++progress); Data.getInstance().updateCategories(true); publishProgress(++progress); Data.getInstance().updateFeeds(Data.VCAT_ALL, true); // Cache all articles publishProgress(++progress); Data.getInstance().cacheArticles(false, true); for (Feed f : labels) { if (f.unread == 0) continue; publishProgress(++progress); Data.getInstance().updateArticles(f.id, true, false, false, true); } publishProgress(++progress); Log.i(TAG, "Updating articles took " + (System.currentTimeMillis() - timeArticles) + "ms"); if (onlyArticles) // We are done here.. break; // Initialize other preferences this.cacheSizeMax = Controller.getInstance().cacheFolderMaxSize() * Utils.MB; this.imageCache = Controller.getInstance().getImageCache(); if (imageCache == null) break; imageCache.fillMemoryCacheFromDisk(); downloadImages(); taskCount = DEFAULT_TASK_COUNT + labels.size(); publishProgress(++progress); purgeCache(); Log.i(TAG, String.format("Cache: %s MB (Limit: %s MB, took %s seconds)", folderSize / 1048576, cacheSizeMax / 1048576, (System.currentTimeMillis() - start) / Utils.SECOND)); break; } // Cleanup publishProgress(Integer.MAX_VALUE); // Call onCacheEnd() requestStop(); return null; } /** * Calls the parent method to update the progress-bar in the UI while articles are refreshed. This is not called * anymore from the moment on when the image-downloading starts. */ @Override protected void onProgressUpdate(Integer... values) { if (parent != null) { if (values[0] == Integer.MAX_VALUE) { parent.onCacheEnd(); } else { parent.onCacheProgress(taskCount, values[0]); } } } @SuppressLint("UseSparseArrays") private void downloadImages() { long time = System.currentTimeMillis(); // DownloadImageTask[] tasks = new DownloadImageTask[DOWNLOAD_IMAGES_THREADS]; map = new HashMap<Integer, ImageCacher.DownloadImageTask>(); ArrayList<Article> articles = DBHelper.getInstance().queryArticlesForImagecache(); taskCount = articles.size(); Log.d(TAG, "Articles count for image caching: " + taskCount); for (Article article : articles) { int articleId = article.id; // Log.d(TAG, "Cache images for article ID: " + articleId); // Get images included in HTML Set<String> set = new HashSet<String>(); for (String url : findAllImageUrls(article.content)) { if (!imageCache.containsKey(url)) set.add(url); } // Log.d(TAG, "Amount of uncached images for article ID " + articleId + ":" + set.size()); // Get images from attachments separately for (String url : article.attachments) { for (String ext : FileUtils.IMAGE_EXTENSIONS) { if (url.toLowerCase(Locale.getDefault()).contains("." + ext) && !imageCache.containsKey(url)) { set.add(url); break; } } } // Log.d(TAG, "Total amount of uncached images for article ID " + articleId + ":" + set.size()); if (!set.isEmpty()) { DownloadImageTask task = new DownloadImageTask(imageCache, articleId, StringSupport.setToArray(set)); handler.post(task); map.put(articleId, task); } else { DBHelper.getInstance().updateArticleCachedImages(articleId, 0); } if (downloaded > cacheSizeMax) { Log.w(TAG, "Stopping download, downloaded data exceeds cache-size-limit from options."); break; } } long timeWait = System.currentTimeMillis(); while (!map.isEmpty()) { synchronized (map) { try { // Only wait for 10 Minutes if (System.currentTimeMillis() - timeWait > Utils.MINUTE * 10) break; map.wait(Utils.SECOND); map.notifyAll(); } catch (InterruptedException e) { Log.d(TAG, "Got an InterruptedException!"); } } } Log.i(TAG, "Downloading images took " + (System.currentTimeMillis() - time) + "ms"); } public class DownloadImageTask implements Runnable { // Max size for one image private final long maxFileSize = Controller.getInstance().cacheImageMaxSize() * Utils.KB; private final long minFileSize = Controller.getInstance().cacheImageMinSize() * Utils.KB; private ImageCache imageCache; private int articleId; private String[] fileUrls; public DownloadImageTask(ImageCache cache, int articleId, String... params) { this.imageCache = cache; this.articleId = articleId; this.fileUrls = params; } @Override public void run() { long size = 0; try { Log.d(TAG, "maxFileSize = " + maxFileSize + " and minFileSize = " + minFileSize); DBHelper.getInstance().insertArticleFiles(articleId, fileUrls); for (String url : fileUrls) { size = FileUtils.downloadToFile(url, imageCache.getCacheFile(url), maxFileSize, minFileSize); if (size <= 0) { DBHelper.getInstance().markRemoteFileCached(url, false, -size); } else { DBHelper.getInstance().markRemoteFileCached(url, true, size); } } } catch (Throwable t) { t.printStackTrace(); } finally { synchronized (map) { if (downloaded > 0) downloaded += size; map.remove(articleId); publishProgress(++progressImageDownload); map.notifyAll(); } } } } /** * cache cleanup */ private void purgeCache() { long time = System.currentTimeMillis(); folderSize = DBHelper.getInstance().getCachedFilesSize(); if (folderSize > cacheSizeMax) { Collection<RemoteFile> rfs = DBHelper.getInstance().getUncacheFiles(folderSize - cacheSizeMax); Log.d(TAG, "Found " + rfs.size() + " cached files for deletion"); ArrayList<Integer> rfIds = new ArrayList<Integer>(rfs.size()); for (RemoteFile rf : rfs) { File file = imageCache.getCacheFile(rf.url); if (file.exists() && !file.delete()) Log.w(TAG, "File " + file.getAbsolutePath() + " was not deleted!"); else Log.w(TAG, "WTF."); rfIds.add(rf.id); } DBHelper.getInstance().markRemoteFilesNonCached(rfIds); } Log.i(TAG, "Purging cache took " + (System.currentTimeMillis() - time) + "ms"); } /** * Searches for cached versions of the given image and returns the local URL to access the file. * * @param url * the original URL * @return the local URL or null if no image in cache or if the file couldn't be found or another thread is creating * the imagecache at the moment. */ public static String getCachedImageUrl(String url) { ImageCache cache = Controller.getInstance().getImageCache(false); if (cache != null && cache.containsKey(url)) { StringBuilder sb = new StringBuilder(); sb.append(cache.getDiskCacheDirectory()); sb.append(File.separator); sb.append(cache.getFileNameForKey(url)); File file = new File(sb.toString()); if (file.exists()) { sb.insert(0, "file://"); // Add "file:" at the beginning.. return sb.toString(); } } return null; } /** * Searches the given html code for img-Tags and filters out all src-attributes, beeing URLs to images. * * @param html * the html code which is to be searched * @return a set of URLs in their string representation */ public static Set<String> findAllImageUrls(String html) { Set<String> ret = new LinkedHashSet<String>(); if (html == null || html.length() < 10) return ret; int i = html.indexOf("<img"); if (i == -1) return ret; // Filter out URLs without leading http, we cannot work with relative URLs (yet?). Matcher m = Utils.findImageUrlsPattern.matcher(html.substring(i, html.length())); while (m.find()) { String url = m.group(1); if (url.startsWith("http")) { ret.add(url); continue; } } return ret; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/imageCache/ImageCacher.java
Java
gpl3
14,985
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.utils; import android.annotation.SuppressLint; import android.content.Context; import android.os.PowerManager; @SuppressLint("Wakelock") public abstract class WakeLocker { private static final String TAG = WakeLocker.class.getSimpleName(); private static PowerManager.WakeLock wakeLock; public static void acquire(Context ctx) { if (wakeLock != null) wakeLock.release(); PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.acquire(); } public static void release() { if (wakeLock != null) wakeLock.release(); wakeLock = null; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/WakeLocker.java
Java
gpl3
1,342
package org.ttrssreader.utils; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import org.ttrssreader.controllers.Controller; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.sqlite.SQLiteException; import android.os.Build; import android.util.Log; /** * Exception report delivery via email and user interaction. Avoids giving an app the * permission to access the Internet. * * @author Ryan Fischbach <br> * Blackmoon Info Tech Services<br> * * Source has been released to the public as is and without any warranty. */ public class PostMortemReportExceptionHandler implements UncaughtExceptionHandler, Runnable { protected static final String TAG = PostMortemReportExceptionHandler.class.getSimpleName(); public static final String ExceptionReportFilename = "postmortem.trace"; // "app label + this tag" = email subject private static final String MSG_SUBJECT_TAG = "Exception Report"; // email will be sent to this account the following may be something you wish to consider localizing private static final String MSG_SENDTO = "ttrss@nilsbraden.de"; private static final String MSG_BODY = "Please help by sending this email. " + "No personal information is being sent (you can check by reading the rest of the email)."; private Thread.UncaughtExceptionHandler mDefaultUEH; private Activity mAct = null; public PostMortemReportExceptionHandler(Activity aAct) { mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler(); mAct = aAct; } /** * Call this method after creation to start protecting all code thereafter. */ public void initialize() { if (mAct == null) throw new NullPointerException(); // Ignore crashreport if user has chosen to ignore it if (Controller.getInstance().isNoCrashreports()) { Log.w(TAG, "User has disabled error reporting."); return; } // Ignore crashreport if this version isn't the newest from market int latest = Controller.getInstance().appLatestVersion(); int current = Utils.getAppVersionCode(mAct); if (latest > current) { Log.w(TAG, "App is not updated, error reports are disabled."); return; } if ((mAct.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { Log.w(TAG, "Application runs with DEBUGGABLE=true, error reports are disabled."); return; } sendDebugReportToAuthor(); // in case a previous error did not get sent to the email app Thread.setDefaultUncaughtExceptionHandler(this); } /** * Call this method at the end of the protected code, usually in {@link finalize()}. */ public void restoreOriginalHandler() { if (Thread.getDefaultUncaughtExceptionHandler().equals(this)) Thread.setDefaultUncaughtExceptionHandler(mDefaultUEH); } @Override protected void finalize() throws Throwable { restoreOriginalHandler(); super.finalize(); } @Override public void uncaughtException(Thread t, Throwable e) { boolean handleException = true; if (e instanceof SecurityException) { // Cannot be reproduced, seems to be related to Cyanogenmod with Android 4.0.4 on some devices: // http://stackoverflow.com/questions/11025182/webview-java-lang-securityexception-no-permission-to-modify-given-thread if (e.getMessage().toLowerCase(Locale.ENGLISH).contains("no permission to modify given thread")) { Log.w(TAG, "Error-Reporting for Exception \"no permission to modify given thread\" is disabled."); handleException = false; } } if (e instanceof SQLiteException) { if (e.getMessage().toLowerCase(Locale.ENGLISH).contains("database is locked")) { Log.w(TAG, "Error-Reporting for Exception \"database is locked\" is disabled."); handleException = false; } } if (handleException) submit(e); // do not forget to pass this exception through up the chain bubbleUncaughtException(t, e); } /** * Send the Exception up the chain, skipping other handlers of this type so only 1 report is sent. * * @param t * - thread object * @param e * - exception being handled */ protected void bubbleUncaughtException(Thread t, Throwable e) { if (mDefaultUEH != null) { if (mDefaultUEH instanceof PostMortemReportExceptionHandler) ((PostMortemReportExceptionHandler) mDefaultUEH).bubbleUncaughtException(t, e); else mDefaultUEH.uncaughtException(t, e); } } /** * Return a string containing the device environment. * * @return Returns a string with the device info used for debugging. */ public String getDeviceEnvironment() { // app environment PackageManager pm = mAct.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(mAct.getPackageName(), 0); } catch (NameNotFoundException nnfe) { // doubt this will ever run since we want info about our own package pi = new PackageInfo(); pi.versionName = "unknown"; pi.versionCode = 69; } Date theDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss_zzz", Locale.ENGLISH); StringBuilder s = new StringBuilder(); s.append("--------- Application ---------------------\n"); s.append("Version = " + Controller.getInstance().getLastVersionRun() + "\n"); s.append("VersionCode = " + (pi != null ? pi.versionCode : "null") + "\n"); s.append("-------------------------------------------\n\n"); s.append("--------- Environment ---------------------\n"); s.append("Time = " + sdf.format(theDate) + "\n"); try { Field theMfrField = Build.class.getField("MANUFACTURER"); s.append("Make = " + theMfrField.get(null) + "\n"); } catch (Exception e) { } s.append("Brand = " + Build.BRAND + "\n"); s.append("Device = " + Build.DEVICE + "\n"); s.append("Model = " + Build.MODEL + "\n"); s.append("Id = " + Build.ID + "\n"); s.append("Fingerprint = " + Build.FINGERPRINT + "\n"); s.append("Product = " + Build.PRODUCT + "\n"); s.append("Locale = " + mAct.getResources().getConfiguration().locale.getDisplayName() + "\n"); s.append("Res = " + mAct.getResources().getDisplayMetrics().toString() + "\n"); s.append("-------------------------------------------\n\n"); s.append("--------- Firmware -----------------------\n"); s.append("SDK = " + Build.VERSION.SDK_INT + "\n"); s.append("Release = " + Build.VERSION.RELEASE + "\n"); s.append("Inc = " + Build.VERSION.INCREMENTAL + "\n"); s.append("-------------------------------------------\n\n"); return s.toString(); } /** * Return the application's friendly name. * * @return Returns the application name as defined by the android:name attribute. */ public CharSequence getAppName() { PackageManager pm = mAct.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(mAct.getPackageName(), 0); return pi.applicationInfo.loadLabel(pm); } catch (NameNotFoundException nnfe) { // doubt this will ever run since we want info about our own package return mAct.getPackageName(); } } /** * If subactivities create their own report handler, report all Activities as a trace list. * A separate line is included if a calling activity/package is detected with the Intent it supplied. * * @param aTrace * - pass in null to force a new list to be created * @return Returns the list of Activities in the handler chain. */ public LinkedList<CharSequence> getActivityTrace(LinkedList<CharSequence> aTrace) { if (aTrace == null) aTrace = new LinkedList<CharSequence>(); aTrace.add(mAct.getLocalClassName() + " (" + mAct.getTitle() + ")"); if (mAct.getCallingActivity() != null) aTrace.add(mAct.getCallingActivity().toString() + " (" + mAct.getIntent().toString() + ")"); else if (mAct.getCallingPackage() != null) aTrace.add(mAct.getCallingPackage().toString() + " (" + mAct.getIntent().toString() + ")"); if (mDefaultUEH != null && mDefaultUEH instanceof PostMortemReportExceptionHandler) ((PostMortemReportExceptionHandler) mDefaultUEH).getActivityTrace(aTrace); return aTrace; } /** * Create a report based on the given exception. * * @param aException * - exception to report on * @return Returns a string with a lot of debug information. */ public String getDebugReport(Throwable aException) { StringBuilder theErrReport = new StringBuilder(); theErrReport.append(getDeviceEnvironment()); theErrReport.append(getAppName() + " generated the following exception:\n"); theErrReport.append(aException.toString() + "\n\n"); // activity stack trace List<CharSequence> theActivityTrace = getActivityTrace(null); if (theActivityTrace != null && theActivityTrace.size() > 0) { theErrReport.append("--------- Activity Stacktrace -------------\n"); for (int i = 0; i < theActivityTrace.size(); i++) { theErrReport.append(" " + theActivityTrace.get(i) + "\n"); }// for theErrReport.append("-------------------------------------------\n\n"); } if (aException != null) { // instruction stack trace StackTraceElement[] theStackTrace = aException.getStackTrace(); if (theStackTrace.length > 0) { theErrReport.append("--------- Instruction Stacktrace ----------\n"); for (int i = 0; i < theStackTrace.length; i++) { theErrReport.append(" " + theStackTrace[i].toString() + "\n"); }// for theErrReport.append("-------------------------------------------\n\n"); } // if the exception was thrown in a background thread inside // AsyncTask, then the actual exception can be found with getCause Throwable theCause = aException.getCause(); if (theCause != null) { theErrReport.append("--------- Cause ---------------------------\n"); theErrReport.append(theCause.toString() + "\n\n"); theStackTrace = theCause.getStackTrace(); for (int i = 0; i < theStackTrace.length; i++) { theErrReport.append(" " + theStackTrace[i].toString() + "\n"); }// for theErrReport.append("-------------------------------------------\n\n"); } } theErrReport.append("END REPORT."); return theErrReport.toString(); } /** * Write the given debug report to the file system. * * @param aReport * - the debug report */ protected void saveDebugReport(String aReport) { // save report to file try { FileOutputStream theFile = mAct.openFileOutput(ExceptionReportFilename, Context.MODE_PRIVATE); theFile.write(aReport.getBytes()); theFile.close(); } catch (IOException ioe) { // error during error report needs to be ignored, do not wish to start infinite loop } } /** * Read in saved debug report and send to email app. */ public void sendDebugReportToAuthor() { String theLine = ""; String theTrace = ""; try { BufferedReader theReader = new BufferedReader(new InputStreamReader( mAct.openFileInput(ExceptionReportFilename))); while ((theLine = theReader.readLine()) != null) { theTrace += theLine + "\n"; } if (sendDebugReportToAuthor(theTrace)) { mAct.deleteFile(ExceptionReportFilename); } } catch (FileNotFoundException eFnf) { // nothing to do } catch (IOException eIo) { // not going to report } } /** * Send the given report to email app. * * @param aReport * - the debug report to send * @return Returns true if the email app was launched regardless if the email was sent. */ public Boolean sendDebugReportToAuthor(String aReport) { if (aReport != null) { Intent theIntent = new Intent(Intent.ACTION_SEND); String theSubject = getAppName() + " " + MSG_SUBJECT_TAG; String theBody = "\n" + MSG_BODY + "\n\n" + aReport + "\n\n"; theIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { MSG_SENDTO }); theIntent.putExtra(Intent.EXTRA_TEXT, theBody); theIntent.putExtra(Intent.EXTRA_SUBJECT, theSubject); theIntent.setType("message/rfc822"); Boolean hasSendRecipients = (mAct.getPackageManager().queryIntentActivities(theIntent, 0).size() > 0); if (hasSendRecipients) { mAct.startActivity(theIntent); return true; } else { return false; } } else { return true; } } @Override public void run() { sendDebugReportToAuthor(); } /** * Create an exception report and start an email with the contents of the report. * * @param e * - the exception */ public void submit(Throwable e) { String theErrReport = getDebugReport(e); saveDebugReport(theErrReport); // try to send file contents via email (need to do so via the UI thread) mAct.runOnUiThread(this); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/PostMortemReportExceptionHandler.java
Java
gpl3
15,560
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.utils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import com.google.common.collect.MapMaker; /** * <p> * A simple 2-level cache consisting of a small and fast in-memory cache (1st level cache) and an (optional) slower but * bigger disk cache (2nd level cache). For disk caching, either the application's cache directory or the SD card can be * used. Please note that in the case of the app cache dir, Android may at any point decide to wipe that entire * directory if it runs low on internal storage. The SD card cache <i>must</i> be managed by the application, e.g. by * calling {@link #wipe} whenever the app quits. * </p> * <p> * When pulling from the cache, it will first attempt to load the data from memory. If that fails, it will try to load * it from disk (assuming disk caching is enabled). If that succeeds, the data will be put in the in-memory cache and * returned (read-through). Otherwise it's a cache miss. * </p> * <p> * Pushes to the cache are always write-through (i.e. the data will be stored both on disk, if disk caching is enabled, * and in memory). * </p> * * @author Matthias Kaeppler * @author Nils Braden (modified some stuff) */ public abstract class AbstractCache<KeyT, ValT> implements Map<KeyT, ValT> { protected boolean isDiskCacheEnabled; protected String diskCacheDir; protected ConcurrentMap<KeyT, ValT> cache; /** * Creates a new cache instance. * * @param name * a human readable identifier for this cache. Note that this value will be used to * derive a directory name if the disk cache is enabled, so don't get too creative * here (camel case names work great) * @param initialCapacity * the initial element size of the cache * @param expirationInMinutes * time in minutes after which elements will be purged from the cache (NOTE: this * only affects the memory cache, the disk cache does currently NOT handle element * TTLs!) * @param maxConcurrentThreads * how many threads you think may at once access the cache; this need not be an exact * number, but it helps in fragmenting the cache properly */ public AbstractCache(String name, int initialCapacity, int maxConcurrentThreads) { MapMaker mapMaker = new MapMaker(); mapMaker.initialCapacity(initialCapacity); // mapMaker.expiration(expirationInMinutes * 60, TimeUnit.SECONDS); mapMaker.concurrencyLevel(maxConcurrentThreads); mapMaker.softValues(); this.cache = mapMaker.makeMap(); } /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. * * @return the full absolute path to the directory where files are cached, if the disk cache is * enabled, otherwise null */ public String getDiskCacheDirectory() { return diskCacheDir; } /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Turns a cache key * into the file name that will be used to persist the value to disk. Subclasses must implement * this. * * @param key * the cache key * @return the file name */ public abstract String getFileNameForKey(KeyT key); /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Restores a value * previously persisted to the disk cache. * * @param file * the file holding the cached value * @return the cached value * @throws IOException */ protected abstract ValT readValueFromDisk(File file) throws IOException; /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Persists a value to * the disk cache. * * @param ostream * the file output stream (buffered). * @param value * the cache value to persist * @throws IOException */ protected abstract void writeValueToDisk(BufferedOutputStream ostream, ValT value) throws IOException; private void cacheToDisk(KeyT key, ValT value) { File file = getFileForKey(key); try { file.createNewFile(); file.deleteOnExit(); BufferedOutputStream ostream = new BufferedOutputStream(new FileOutputStream(file)); writeValueToDisk(ostream, value); ostream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } protected File getFileForKey(KeyT key) { return new File(diskCacheDir + "/" + getFileNameForKey(key)); } /** * Reads a value from the cache by probing the in-memory cache, and if enabled and the in-memory * probe was a miss, the disk cache. * * @param elementKey * the cache key * @return the cached value, or null if element was not cached */ @SuppressWarnings("unchecked") public synchronized ValT get(Object elementKey) { KeyT key = (KeyT) elementKey; ValT value = cache.get(key); if (value != null) { // memory hit return value; } // memory miss, try reading from disk File file = getFileForKey(key); if (file.exists()) { // disk hit try { value = readValueFromDisk(file); } catch (IOException e) { // treat decoding errors as a cache miss e.printStackTrace(); return null; } if (value == null) { return null; } cache.put(key, value); return value; } // cache miss return null; } /** * Writes an element to the cache. NOTE: If disk caching is enabled, this will write through to * the disk, which may introduce a performance penalty. */ public synchronized ValT put(KeyT key, ValT value) { if (isDiskCacheEnabled) { cacheToDisk(key, value); } return cache.put(key, value); } public synchronized void putAll(Map<? extends KeyT, ? extends ValT> t) { throw new UnsupportedOperationException(); } /** * Checks if a value is present in the cache. If the disk cached is enabled, this will also * check whether the value has been persisted to disk. * * @param key * the cache key * @return true if the value is cached in memory or on disk, false otherwise */ @SuppressWarnings("unchecked") public synchronized boolean containsKey(Object key) { return cache.containsKey(key) || (isDiskCacheEnabled && getFileForKey((KeyT) key).exists()); } /** * Checks if the given value is currently hold in memory. */ public synchronized boolean containsValue(Object value) { return cache.containsValue(value); } @SuppressWarnings("unchecked") public synchronized ValT remove(Object key) { ValT value = cache.remove(key); if (isDiskCacheEnabled) { File cachedValue = getFileForKey((KeyT) key); if (cachedValue.exists()) { cachedValue.delete(); } } return value; } public Set<KeyT> keySet() { return cache.keySet(); } public Set<Map.Entry<KeyT, ValT>> entrySet() { return cache.entrySet(); } public synchronized int size() { return cache.size(); } public synchronized boolean isEmpty() { return cache.isEmpty(); } public synchronized void clear() { cache.clear(); if (isDiskCacheEnabled) { File[] cachedFiles = new File(diskCacheDir).listFiles(); if (cachedFiles == null) { return; } for (File f : cachedFiles) { f.delete(); } } } public Collection<ValT> values() { return cache.values(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/AbstractCache.java
Java
gpl3
9,318
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.utils; import java.io.File; import java.io.Serializable; import java.util.Comparator; /** * Compare the <b>last modified date/time</b> of two files for order * (see {@link File#lastModified()}). * <p> * This comparator can be used to sort lists or arrays of files by their last modified date/time. * <p> * Example of sorting a list of files using the {@link #LASTMODIFIED_COMPARATOR} singleton instance: * * <pre> * List&lt;File&gt; list = ... * Collections.sort(list, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR); * </pre> * <p> * Example of doing a <i>reverse</i> sort of an array of files using the {@link #LASTMODIFIED_REVERSE} singleton * instance: * * <pre> * File[] array = ... * Arrays.sort(array, LastModifiedFileComparator.LASTMODIFIED_REVERSE); * </pre> * <p> * * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $ * @since Commons IO 1.4 */ @SuppressWarnings("serial") public class FileDateComparator implements Comparator<File>, Serializable { /** Last modified comparator instance */ public static final Comparator<File> LASTMODIFIED_COMPARATOR = new FileDateComparator(); /** * Compare the last the last modified date/time of two files. * * @param obj1 * The first file to compare * @param obj2 * The second file to compare * @return a negative value if the first file's lastmodified date/time * is less than the second, zero if the lastmodified date/time are the * same and a positive value if the first files lastmodified date/time * is greater than the second file. * */ public int compare(File obj1, File obj2) { long result = obj1.lastModified() - obj2.lastModified(); if (result < 0) { return -1; } else if (result > 0) { return 1; } else { return 0; } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/FileDateComparator.java
Java
gpl3
2,812
// @formatter:off /** * <p>Encodes and decodes to and from Base64 notation.</p> * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> * * <p>Example:</p> * * <code>String encoded = Base64.encode( myByteArray );</code> * <br /> * <code>byte[] myByteArray = Base64.decode( encoded );</code> * * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass * several pieces of information to the encoder. In the "higher level" methods such as * encodeBytes( bytes, options ) the options parameter can be used to indicate such * things as first gzipping the bytes before encoding them, not inserting linefeeds, * and encoding using the URL-safe and Ordered dialects.</p> * * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, * Section 2.1, implementations should not add line feeds unless explicitly told * to do so. I've got Base64 set to this behavior now, although earlier versions * broke lines by default.</p> * * <p>The constants defined in Base64 can be OR-ed together to combine options, so you * might make a call like this:</p> * * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code> * <p>to compress the data before encoding it and then making the output have newline characters.</p> * <p>Also...</p> * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.3.7 */ package org.ttrssreader.utils; public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding in first bit. Value is one. */ public final static int ENCODE = 1; /** Specify decoding in first bit. Value is zero. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed in second bit. Value is two. */ public final static int GZIP = 2; /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */ public final static int DONT_GUNZIP = 4; /** Do break lines when encoding. Value is 8. */ public final static int DO_BREAK_LINES = 8; /** * Encode using Base64-like encoding that is URL- and Filename-safe as described * in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * It is important to note that data encoded this way is <em>not</em> officially valid Base64, * or at the very least should not be called Base64 without also specifying that is * was encoded using the URL- and Filename-safe dialect. */ public final static int URL_SAFE = 16; /** * Encode using the special "ordered" dialect of Base64 described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ public final static int ORDERED = 32; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "US-ASCII"; private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ /** The 64 valid Base64 values. */ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ private final static byte[] _STANDARD_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] _STANDARD_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ /** * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." */ private final static byte[] _URL_SAFE_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' }; /** * Used in decoding URL- and Filename-safe dialects of Base64. */ private final static byte[] _URL_SAFE_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ /** * I don't get the point of this technique, but someone requested it, * and it is described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ private final static byte[] _ORDERED_ALPHABET = { (byte)'-', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'_', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' }; /** * Used in decoding the "ordered" dialect of Base64. */ private final static byte[] _ORDERED_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ /** * Returns one of the _SOMETHING_ALPHABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getAlphabet( int options ) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_ALPHABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_ALPHABET; } else { return _STANDARD_ALPHABET; } } // end getAlphabet /** * Returns one of the _SOMETHING_DECODABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED and URL_SAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getDecodabet( int options ) { if( (options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_DECODABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_DECODABET; } else { return _STANDARD_DECODABET; } } // end getAlphabet /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); return b4; } // end encode3to4 /** * <p>Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>.</p> * <p>This is the lowest level of the encoding methods with * all possible parameters.</p> * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options ) { byte[] ALPHABET = getAlphabet( options ); // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> ByteBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); encoded.put(enc4); } // end input remaining } /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> CharBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); for( int i = 0; i < 4; i++ ){ encoded.put( (char)(enc4[i] & 0xFF) ); } } // end input remaining } /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @throws java.io.IOException if there is an error * @throws NullPointerException if serializedObject is null * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) throws java.io.IOException { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @return The data in Base64-encoded form * @throws NullPointerException if source array is null * @since 1.4 */ public static String encodeBytes( byte[] source ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * <p>As of v 2.3, if there is an error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @return The Base64-encoded data as a String * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes( source, off, len, NO_OPTIONS ); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { byte[] encoded = encodeBytesToBytes( source, off, len, options ); // Return value according to relevant encoding. try { return new String( encoded, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( encoded ); } // end catch } // end encodeBytes /** * Similar to {@link #encodeBytes(byte[])} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @return The Base64-encoded data as a byte[] (of ASCII characters) * @throws NullPointerException if source array is null * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source ) { byte[] encoded = null; try { encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); } catch( java.io.IOException ex ) { assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); } return encoded; } /** * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } // end encodeBytesToBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * <p>This is the lowest level of the decoding methods with * all possible parameters.</p> * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param options alphabet type is pulled from this (standard, url-safe, ordered) * @return the number of decoded bytes converted * @throws NullPointerException if source or destination arrays are null * @throws IllegalArgumentException if srcOffset or destOffset are invalid * or there is not enough room in the array. * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Source array was null." ); } // end if if( destination == null ){ throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if byte[] DECODABET = getDecodabet( options ); // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; } } // end decodeToBytes /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @return decoded data * @since 2.3.1 */ public static byte[] decode( byte[] source ) throws java.io.IOException { byte[] decoded = null; // try { decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); // } catch( java.io.IOException ex ) { // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); // } return decoded; } /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @param options Can specify options such as alphabet type to use * @return decoded data * @throws java.io.IOException If bogus characters exist in source data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len, int options ) throws java.io.IOException { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Cannot decode null source array." ); } // end if if( off < 0 || off + len > source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); } // end if if( len == 0 ){ return new byte[0]; }else if( len < 4 ){ throw new IllegalArgumentException( "Base64-encoded string must have at least four characters, but length specified was " + len ); } // end if byte[] DECODABET = getDecodabet( options ); int len34 = len * 3 / 4; // Estimate on array size byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; // Keep track of where we're writing byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space int b4Posn = 0; // Keep track of four byte input buffer int i = 0; // Source array counter byte sbiDecode = 0; // Special value from DECODABET for( i = off; i < off+len; i++ ) { // Loop through source sbiDecode = DECODABET[ source[i]&0xFF ]; // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = source[i]; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( source[i] == EQUALS_SIGN ) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { // There's a bad input character in the Base64 stream. throw new java.io.IOException( String.format( "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @throws java.io.IOException If there is a problem * @since 1.4 */ public static byte[] decode( String s ) throws java.io.IOException { return decode( s, NO_OPTIONS ); } /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @param options encode options such as URL_SAFE * @return the decoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if <tt>s</tt> is null * @since 1.4 */ public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 1.5 */ public static Object decodeToObject( String encodedObject ) throws java.io.IOException, java.lang.ClassNotFoundException { return decodeToObject(encodedObject,NO_OPTIONS,null); } /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * If <tt>loader</tt> is not null, it will be the class loader * used when deserializing. * * @param encodedObject The Base64 data to decode * @param options Various parameters related to decoding * @param loader Optional class loader to use in deserializing classes. * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 2.3.4 */ public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class<?> c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if dataToEncode is null * @since 2.1 */ public static void encodeToFile( byte[] dataToEncode, String filename ) throws java.io.IOException { if( dataToEncode == null ){ throw new NullPointerException( "Data to encode was null." ); } // end iff Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end encodeToFile /** * Convenience method for decoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @throws java.io.IOException if there is an error * @since 2.1 */ public static void decodeToFile( String dataToDecode, String filename ) throws java.io.IOException { Base64.OutputStream bos = null; try{ bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading encoded data * @return decoded byte array * @throws java.io.IOException if there is an error * @since 2.1 */ public static byte[] decodeFromFile( String filename ) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading binary data * @return base64-encoded string * @throws java.io.IOException if there is an error * @since 2.1 */ public static String encodeFromFile( String filename ) throws java.io.IOException { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /** * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void encodeFileToFile( String infile, String outfile ) throws java.io.IOException { String encoded = Base64.encodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end encodeFileToFile /** * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void decodeFileToFile( String infile, String outfile ) throws java.io.IOException { byte[] decoded = Base64.decodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( decoded ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end decodeFileToFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters private int options; // Record options used to create the stream. private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.options = options; // Record for later this.breakLines = (options & DO_BREAK_LINES) > 0; this.encode = (options & ENCODE) > 0; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; this.decodabet = getDecodabet(options); } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ @Override public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } else { break; // out of for loop } // end else: end of stream } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; // Must be end of stream } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) { break; // Reads a -1 if end of stream } // end if: end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0, options ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ){ return -1; } // end if: got data if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) { position = -1; } // end if: end return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ @Override public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); if( b >= 0 ) { dest[off + i] = (byte) b; } else if( i == 0 ) { return -1; } else { break; // Out of 'for' loop } // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; private int options; // Record for later private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DO_BREAK_LINES) != 0; this.encode = (options & ENCODE) != 0; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; this.options = options; this.decodabet = getDecodabet(options); } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ @Override public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to encode. this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { this.out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to output. int len = Base64.decode4to3( buffer, 0, b4, 0, options ); out.write( b4, 0, len ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ @Override public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. * @throws java.io.IOException if there's an error. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position, options ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ @Override public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @throws java.io.IOException if there's an error flushing * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64 //@formatter:on
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/Base64.java
Java
gpl3
79,994
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.utils; import java.net.URI; import java.net.URISyntaxException; import java.util.Set; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.preferences.Constants; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ClipData; import android.content.ClipDescription; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.util.Log; public class Utils { protected static final String TAG = Utils.class.getSimpleName(); public static final long SECOND = 1000; public static final long MINUTE = 60 * SECOND; public static final long HOUR = 60 * MINUTE; public static final long DAY = 24 * HOUR; public static final long WEEK = 7 * DAY; public static final long MONTH = 31 * DAY; public static final long KB = 1024; public static final long MB = KB * KB; /** * The maximum number of articles to store. */ public static final int ARTICLE_LIMIT = 5000; /** * Min supported versions of the Tiny Tiny RSS Server */ public static final int SERVER_VERSION = 150; /** * Vibrate-Time for vibration when end of list is reached */ public static final long SHORT_VIBRATE = 50; /** * The time after which data will be fetched again from the server if asked for the data */ public static final long UPDATE_TIME = MINUTE * 30; public static final long HALF_UPDATE_TIME = UPDATE_TIME / 2; /** * The time after which the DB and other data will be cleaned up again, */ public static final long CLEANUP_TIME = DAY; /** * The Pattern to match image-urls inside HTML img-tags. */ public static final Pattern findImageUrlsPattern = Pattern.compile("<img[^>]+?src=[\"']([^\\\"']*)", Pattern.CASE_INSENSITIVE); private static final int ID_RUNNING = 4564561; private static final int ID_FINISHED = 7897891; /* * Check if this is the first run of the app, if yes, returns false. */ public static boolean checkIsFirstRun(Context a) { return Controller.getInstance().newInstallation(); } /* * Check if a new version of the app was installed, returns true if this is the case. This also triggers the reset * of the preference noCrashreportsUntilUpdate since with a new update the crash reporting should now be enabled * again. */ public static boolean checkIsNewVersion(Context c) { String thisVersion = getAppVersionName(c); String lastVersionRun = Controller.getInstance().getLastVersionRun(); Controller.getInstance().setLastVersionRun(thisVersion); if (thisVersion.equals(lastVersionRun)) { // No new version installed, perhaps a new version exists // Only run task once for every session and only if we are online if (!checkConnected((ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE))) return false; if (AsyncTask.Status.PENDING.equals(updateVersionTask.getStatus())) updateVersionTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return false; } else { // New update was installed, reset noCrashreportsUntilUpdate and return true to display the changelog... Controller.getInstance().setNoCrashreportsUntilUpdate(false); return true; } } /* * Checks the config for a user-defined server, returns true if the config is invalid and the user has not yet * entered a valid server adress. */ public static boolean checkIsConfigInvalid() { try { URI uri = Controller.getInstance().uri(); if (uri == null || uri.toASCIIString().equals(Constants.URL_DEFAULT + Controller.JSON_END_URL)) { return true; } } catch (URISyntaxException e) { return true; } return false; } /** * Retrieves the packaged version-code of the application * * @param c * - The Activity to retrieve the current version * @return the version-string */ public static int getAppVersionCode(Context c) { int result = 0; try { PackageManager manager = c.getPackageManager(); PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0); result = info.versionCode; } catch (NameNotFoundException e) { Log.w(TAG, "Unable to get application version: " + e.getMessage()); result = 0; } return result; } /** * Retrieves the packaged version-name of the application * * @param c * - The Activity to retrieve the current version * @return the version-string */ public static String getAppVersionName(Context c) { String result = ""; try { PackageManager manager = c.getPackageManager(); PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0); result = info.versionName; } catch (NameNotFoundException e) { Log.w(TAG, "Unable to get application version: " + e.getMessage()); result = ""; } return result; } /** * Checks if the option to work offline is set or if the data-connection isn't established, else returns true. If we * are about to connect it waits for maximum one second and then returns the network state without waiting anymore. * * @param cm * @return */ public static boolean isConnected(ConnectivityManager cm) { if (Controller.getInstance().workOffline()) return false; return checkConnected(cm); } /** * Wrapper for Method checkConnected(ConnectivityManager cm, boolean onlyWifi) * * @param cm * @return */ public static boolean checkConnected(ConnectivityManager cm) { return checkConnected(cm, Controller.getInstance().onlyUseWifi()); } /** * Only checks the connectivity without regard to the preferences * * @param cm * @return */ private static boolean checkConnected(ConnectivityManager cm, boolean onlyWifi) { if (cm == null) return false; NetworkInfo info; if (onlyWifi) { info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } else { info = cm.getActiveNetworkInfo(); } if (info == null) return false; return info.isConnected(); } public static void showFinishedNotification(String content, int time, boolean error, Context context) { showFinishedNotification(content, time, error, context, new Intent()); } /** * Shows a notification with the given parameters * * @param content * the string to display * @param time * how long the process took * @param error * set to true if an error occured * @param context * the context */ public static void showFinishedNotification(String content, int time, boolean error, Context context, Intent intent) { NotificationManager mNotMan = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.icon; CharSequence title = String.format((String) context.getText(R.string.Utils_DownloadFinishedTitle), time); CharSequence ticker = context.getText(R.string.Utils_DownloadFinishedTicker); CharSequence text = content; if (content == null) text = context.getText(R.string.Utils_DownloadFinishedText); if (error) { icon = R.drawable.icon; title = context.getText(R.string.Utils_DownloadErrorTitle); ticker = context.getText(R.string.Utils_DownloadErrorTicker); } Notification notification = buildNotification(context, icon, ticker, title, text, true, intent); mNotMan.notify(ID_FINISHED, notification); } public static void showRunningNotification(Context context, boolean finished) { showRunningNotification(context, finished, new Intent()); } /** * Shows a notification indicating that something is running. When called with finished=true it removes the * notification. * * @param context * the context * @param finished * if the notification is to be removed */ public static void showRunningNotification(Context context, boolean finished, Intent intent) { NotificationManager mNotMan = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // if finished remove notification and return, else display notification if (finished) { mNotMan.cancel(ID_RUNNING); return; } int icon = R.drawable.notification_icon; CharSequence title = context.getText(R.string.Utils_DownloadRunningTitle); CharSequence ticker = context.getText(R.string.Utils_DownloadRunningTicker); CharSequence text = context.getText(R.string.Utils_DownloadRunningText); Notification notification = buildNotification(context, icon, ticker, title, text, true, intent); mNotMan.notify(ID_RUNNING, notification); } /** * Reads a file from my webserver and parses the content. It containts the version code of the latest supported * version. If the version of the installed app is lower then this the feature "Send mail with stacktrace on error" * will be disabled to make sure I only receive "new" Bugreports. */ private static AsyncTask<Void, Void, Void> updateVersionTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // Check last appVersionCheckDate long last = Controller.getInstance().appVersionCheckTime(); if ((System.currentTimeMillis() - last) < (Utils.HOUR * 4)) return null; // Retrieve remote version int remote = 0; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://nilsbraden.de/android/tt-rss/minSupportedVersion.txt"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity.getContentLength() < 0 || httpEntity.getContentLength() > 100) throw new Exception("Content too long or empty."); String content = EntityUtils.toString(httpEntity); // Only ever read the integer if it matches the regex and is not too long if (content.matches("[0-9]*[\\r\\n]*")) { content = content.replaceAll("[^0-9]*", ""); remote = Integer.parseInt(content); } } catch (Exception e) { } // Store version if (remote > 0) Controller.getInstance().setAppLatestVersion(remote); return null; } }; @SuppressWarnings("deprecation") public static Notification buildNotification(Context context, int icon, CharSequence ticker, CharSequence title, CharSequence text, boolean autoCancel, Intent intent) { Notification notification = null; PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); try { Notification.Builder builder = new Notification.Builder(context); builder.setSmallIcon(icon); builder.setTicker(ticker); builder.setWhen(System.currentTimeMillis()); builder.setContentTitle(title); builder.setContentText(text); builder.setContentIntent(pendingIntent); builder.setAutoCancel(autoCancel); if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) notification = builder.getNotification(); else notification = builder.build(); } catch (Exception re) { Log.e(TAG, "Exception while building notification. Does your device propagate the right API-Level? (" + Build.VERSION.SDK_INT + ")", re); } return notification; } public static String separateItems(Set<?> att, String separator) { if (att == null) return ""; String ret; StringBuilder sb = new StringBuilder(); for (Object s : att) { sb.append(s); sb.append(separator); } if (att.size() > 0) { ret = sb.substring(0, sb.length() - separator.length()); } else { ret = sb.toString(); } return ret; } private static final String REGEX_URL = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; public static boolean validateURL(String url) { return url != null && url.matches(REGEX_URL); } public static String getTextFromClipboard(Context context) { // New Clipboard API ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); if (clipboard.hasPrimaryClip()) { if (!clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) return null; ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0); CharSequence chars = item.getText(); if (chars != null && chars.length() > 0) { return chars.toString(); } else { Uri pasteUri = item.getUri(); if (pasteUri != null) { return pasteUri.toString(); } } } return null; } public static boolean clipboardHasText(Context context) { return (getTextFromClipboard(context) != null); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/Utils.java
Java
gpl3
15,795
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.utils; import java.io.Serializable; import java.util.Comparator; import org.ttrssreader.model.pojos.Label; @SuppressWarnings("serial") public class LabelTitleComparator implements Comparator<Label>, Serializable { public static final Comparator<Label> LABELTITLE_COMPARATOR = new LabelTitleComparator(); public int compare(Label obj1, Label obj2) { if (obj1 == null || obj2 == null) throw new NullPointerException(); return obj1.caption.compareTo(obj2.caption); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/LabelTitleComparator.java
Java
gpl3
1,066
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.utils; import java.util.Date; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import android.content.Context; /** * Provides functionality to automatically format date and time values (or both) depending on settings of the app and * the systems configuration. * * @author Nils Braden */ public class DateUtils { /** * Returns the formatted date and time in the format specified by Controller.dateString() and * Controller.timeString() or if settings indicate the systems configuration should be used it returns the date and * time formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the date and time */ public static String getDateTime(Context context, Date date) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context); return dateFormat.format(date) + " " + timeFormat.format(date); } else { try { // Only display delimiter if both formats are available, if the user did set one to an empty string he // doesn't want to see this information and we can hide the delimiter too. String dateStr = Controller.getInstance().dateString(); String timeStr = Controller.getInstance().timeString(); String delimiter = (dateStr.length() > 0 && timeStr.length() > 0) ? " " : ""; String formatted = dateStr + delimiter + timeStr; return android.text.format.DateFormat.format(formatted, date).toString(); } catch (Exception e) { // Retreat to default date-time-format java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context); return dateFormat.format(date) + " " + timeFormat.format(date); } } } /** * Returns the formatted date in the format specified by Controller.dateString() or if settings indicate the systems * configuration should be used it returns the date formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the date */ public static String getDate(Context context, Date date) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); return dateFormat.format(date); } else { try { String format = Controller.getInstance().dateString(); return android.text.format.DateFormat.format(format, date).toString(); } catch (Exception e) { // Retreat to default date-format String format = context.getResources().getString(R.string.DisplayDateFormatDefault); return android.text.format.DateFormat.format(format, date).toString(); } } } /** * Returns the formatted time in the format specified by Controller.timeString() or if settings indicate the systems * configuration should be used it returns the time formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the time */ public static String getTime(Context context, Date time) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context); return timeFormat.format(time); } else { try { String format = Controller.getInstance().timeString(); return android.text.format.DateFormat.format(format, time).toString(); } catch (Exception e) { // Retreat to default time-format String format = context.getResources().getString(R.string.DisplayTimeFormatDefault); return android.text.format.DateFormat.format(format, time).toString(); } } } /** * Returns the formatted date in the format specified by Controller.dateString() or if settings indicate the systems * configuration should be used it returns the date formatted as specified by the system. * * @param context * the application context * @param dateTime * the date to be formatted * @return a formatted representation of the date */ public static String getDateTimeCustom(Context context, Date dateTime) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); return dateFormat.format(dateTime); } else { try { String format = Controller.getInstance().dateTimeString(); return android.text.format.DateFormat.format(format, dateTime).toString(); } catch (Exception e) { // Retreat to default date-format String format = context.getResources().getString(R.string.DisplayDateTimeFormatDefault); return android.text.format.DateFormat.format(format, dateTime).toString(); } } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/DateUtils.java
Java
gpl3
6,422
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.utils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.ttrssreader.net.SSLSocketFactoryEx; import android.annotation.SuppressLint; import android.os.Environment; public class SSLUtils { public static SSLSocketFactory initSslSocketFactory() throws KeyManagementException, NoSuchAlgorithmException { return initSslSocketFactory(null, null); } @SuppressLint("TrulyRandom") public static SSLSocketFactory initSslSocketFactory(KeyManager[] km, TrustManager[] tm) throws KeyManagementException, NoSuchAlgorithmException { // Apply fix for PRNG from http://android-developers.blogspot.de/2013/08/some-securerandom-thoughts.html PRNGFixes.apply(); SSLSocketFactoryEx factory = new SSLSocketFactoryEx(km, tm, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(factory); return factory; } public static void initPrivateKeystore(String password) throws Exception { KeyStore keystore = SSLUtils.loadKeystore(password); if (keystore == null) return; TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keystore); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, password.toCharArray()); initSslSocketFactory(kmf.getKeyManagers(), tmf.getTrustManagers()); } public static KeyStore loadKeystore(String keystorePassword) throws Exception { KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType()); File file = new File(Environment.getExternalStorageDirectory() + File.separator + FileUtils.SDCARD_PATH_FILES + "store.bks"); if (!file.exists()) return null; InputStream in = new FileInputStream(file); try { trusted.load(in, keystorePassword.toCharArray()); } finally { in.close(); } return trusted; } public static void trustAllCert() throws Exception { X509TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; // Create a trust manager that does not validate certificate chains initSslSocketFactory(null, new TrustManager[] { easyTrustManager }); } public static void trustAllHost() throws Exception { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/SSLUtils.java
Java
gpl3
4,280
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2008 OpenIntents.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.utils; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.res.XmlResourceParser; public class MimeTypeParser { protected static final String TAG_MIMETYPES = "MimeTypes"; protected static final String TAG_TYPE = "type"; public static final String ATTR_EXTENSION = "extension"; public static final String ATTR_MIMETYPE = "mimetype"; private XmlPullParser mXpp; private MimeTypes mMimeTypes; public MimeTypeParser() { } public MimeTypes fromXml(InputStream in) throws XmlPullParserException, IOException { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); mXpp = factory.newPullParser(); mXpp.setInput(new InputStreamReader(in)); return parse(); } public MimeTypes fromXmlResource(XmlResourceParser in) throws XmlPullParserException, IOException { mXpp = in; return parse(); } public MimeTypes parse() throws XmlPullParserException, IOException { mMimeTypes = new MimeTypes(); int eventType = mXpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String tag = mXpp.getName(); if (eventType == XmlPullParser.START_TAG) { if (tag.equals(TAG_MIMETYPES)) { } else if (tag.equals(TAG_TYPE)) { addMimeTypeStart(); } } else if (eventType == XmlPullParser.END_TAG) { if (tag.equals(TAG_MIMETYPES)) { } } eventType = mXpp.next(); } return mMimeTypes; } private void addMimeTypeStart() { String extension = mXpp.getAttributeValue(null, ATTR_EXTENSION); String mimetype = mXpp.getAttributeValue(null, ATTR_MIMETYPE); mMimeTypes.put(extension, mimetype); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/MimeTypeParser.java
Java
gpl3
2,981
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.utils; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.os.Handler; import android.os.Message; import android.os.Process; /** * @see http://stackoverflow.com/questions/7211684/asynctask-executeonexecutor-before-api-level-11/9509184#9509184 * (Source: https://raw.github.com/android/platform_frameworks_base/master/core/java/android/os/AsyncTask.java) */ public abstract class AsyncTask<Params, Progress, Result> { private static final String LOG_TAG = "AsyncTask"; private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final int CORE_POOL_SIZE = CPU_COUNT + 1; private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE = 1; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128); /** * An {@link Executor} that can be used to execute tasks in parallel. */ public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); /** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ // public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static final InternalHandler sHandler = new InternalHandler(); // private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; private static volatile Executor sDefaultExecutor = THREAD_POOL_EXECUTOR; private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); // private static class SerialExecutor implements Executor { // final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); // Runnable mActive; // // public synchronized void execute(final Runnable r) { // mTasks.offer(new Runnable() { // public void run() { // try { // r.run(); // } finally { // scheduleNext(); // } // } // }); // if (mActive == null) { // scheduleNext(); // } // } // // protected synchronized void scheduleNext() { // if ((mActive = mTasks.poll()) != null) { // THREAD_POOL_EXECUTOR.execute(mActive); // } // } // } /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED, } /** @hide Used to force static handler to be created. */ public static void init() { sHandler.getLooper(); } /** @hide */ public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; } /** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // noinspection unchecked return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } } private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params * The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ protected abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground */ protected void onPreExecute() { } /** * <p> * Runs on the UI thread after {@link #doInBackground}. The specified result is the value returned by * {@link #doInBackground}. * </p> * * <p> * This method won't be invoked if the task was cancelled. * </p> * * @param result * The result of the operation computed by {@link #doInBackground}. * * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ protected void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values * The values indicating progress. * * @see #publishProgress * @see #doInBackground */ protected void onProgressUpdate(Progress... values) { } /** * <p> * Runs on the UI thread after {@link #cancel(boolean)} is invoked and {@link #doInBackground(Object[])} has * finished. * </p> * * <p> * The default implementation simply invokes {@link #onCancelled()} and ignores the result. If you write your own * implementation, do not call <code>super.onCancelled(result)</code>. * </p> * * @param result * The result, if any, computed in {@link #doInBackground(Object[])}, can be null * * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled(Result result) { onCancelled(); } /** * <p> * Applications should preferably override {@link #onCancelled(Object)}. This method is invoked by the default * implementation of {@link #onCancelled(Object)}. * </p> * * <p> * Runs on the UI thread after {@link #cancel(boolean)} is invoked and {@link #doInBackground(Object[])} has * finished. * </p> * * @see #onCancelled(Object) * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled() { } /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. If you are calling {@link #cancel(boolean)} on the task, * the value returned by this method should be checked periodically from {@link #doInBackground(Object[])} to end * the task as soon as possible. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mCancelled.get(); } /** * <p> * Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been * cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when * <tt>cancel</tt> is called, this task should never run. If the task has already started, then the * <tt>mayInterruptIfRunning</tt> parameter determines whether the thread executing this task should be interrupted * in an attempt to stop the task. * </p> * * <p> * Calling this method will result in {@link #onCancelled(Object)} being invoked on the UI thread after * {@link #doInBackground(Object[])} returns. Calling this method guarantees that {@link #onPostExecute(Object)} is * never invoked. After invoking this method, you should check the value returned by {@link #isCancelled()} * periodically from {@link #doInBackground(Object[])} to finish the task as early as possible. * </p> * * @param mayInterruptIfRunning * <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled(Object) */ public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException * If the computation was cancelled. * @throws ExecutionException * If the computation threw an exception. * @throws InterruptedException * If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout * Time to wait before cancelling the operation. * @param unit * The time unit for the timeout. * * @return The computed result. * * @throws CancellationException * If the computation was cancelled. * @throws ExecutionException * If the computation threw an exception. * @throws InterruptedException * If the current thread was interrupted * while waiting. * @throws TimeoutException * If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p> * Note: this function schedules the task on a queue for a single background thread or pool of threads depending on * the platform version. When first introduced, AsyncTasks were executed serially on a single background thread. * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed to a pool of threads allowing * multiple tasks to operate in parallel. Starting {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back * to being executed on a single thread to avoid common application errors caused by parallel execution. If you * truly want parallel execution, you can use the {@link #executeOnExecutor} version of this method with * {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings on its use. * * <p> * This method must be invoked on the UI thread. * * @param params * The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException * If {@link #getStatus()} returns either {@link AsyncTask.Status#RUNNING} or * {@link AsyncTask.Status#FINISHED}. * * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) * @see #execute(Runnable) */ public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p> * This method is typically used with {@link #THREAD_POOL_EXECUTOR} to allow multiple tasks to run in parallel on a * pool of threads managed by AsyncTask, however you can also use your own {@link Executor} for custom behavior. * * <p> * <em>Warning:</em> Allowing multiple tasks to run in parallel from a thread pool is generally <em>not</em> what * one wants, because the order of their operation is not defined. For example, if these tasks are used to modify * any state in common (such as writing a file due to a button click), there are no guarantees on the order of the * modifications. Without careful work it is possible in rare cases for the newer version of the data to be * over-written by an older one, leading to obscure data loss and stability issues. Such changes are best executed * in serial; to guarantee such work is serialized regardless of platform version you can use this function with * {@link #SERIAL_EXECUTOR}. * * <p> * This method must be invoked on the UI thread. * * @param exec * The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a * convenient process-wide thread pool for tasks that are loosely coupled. * @param params * The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException * If {@link #getStatus()} returns either {@link AsyncTask.Status#RUNNING} or * {@link AsyncTask.Status#FINISHED}. * * @see #execute(Object[]) */ public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); default: { // Empty } } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; } /** * Convenience version of {@link #execute(Object...)} for use with * a simple Runnable object. See {@link #execute(Object[])} for more * information on the order of execution. * * @see #execute(Object[]) * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) */ public static void execute(Runnable runnable) { sDefaultExecutor.execute(runnable); } /** * This method can be invoked from {@link #doInBackground} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of {@link #onProgressUpdate} on the UI thread. * * {@link #onProgressUpdate} will note be called if the task has been * canceled. * * @param values * The progress values to update the UI with. * * @see #onProgressUpdate * @see #doInBackground */ protected final void publishProgress(Progress... values) { if (!isCancelled()) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({ "rawtypes" }) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/AsyncTask.java
Java
gpl3
19,904
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2008 OpenIntents.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.utils; import java.util.HashMap; import java.util.Locale; import java.util.Map; import android.webkit.MimeTypeMap; public class MimeTypes { private Map<String, String> mMimeTypes; public MimeTypes() { mMimeTypes = new HashMap<String, String>(); } public void put(String type, String extension) { // Convert extensions to lower case letters for easier comparison extension = extension.toLowerCase(Locale.getDefault()); mMimeTypes.put(type, extension); } public String getMimeType(String filename) { String extension = MimeTypes.getExtension(filename); // Let's check the official map first. Webkit has a nice extension-to-MIME map. // Be sure to remove the first character from the extension, which is the "." character. if (extension.length() > 0) { String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1)); if (webkitMimeType != null) { // Found one. Let's take it! return webkitMimeType; } } // Convert extensions to lower case letters for easier comparison extension = extension.toLowerCase(Locale.getDefault()); String mimetype = mMimeTypes.get(extension); if (mimetype == null) mimetype = "*/*"; return mimetype; } public static String getExtension(String uri) { if (uri == null) { return null; } int dot = uri.lastIndexOf("."); if (dot >= 0) { return uri.substring(dot); } else { // No extension. return ""; } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/MimeTypes.java
Java
gpl3
2,584
/* * This software is provided 'as-is', without any express or implied * warranty. In no event will Google be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, as long as the origin is not misrepresented. */ package org.ttrssreader.utils; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.SecureRandom; import java.security.SecureRandomSpi; import java.security.Security; import android.os.Build; import android.os.Process; import android.util.Log; /** * Fixes for the output of the default PRNG having low entropy. * * The fixes need to be applied via {@link #apply()} before any use of Java * Cryptography Architecture primitives. A good place to invoke them is in the * application's {@code onCreate}. */ public final class PRNGFixes { private static final int VERSION_CODE_JELLY_BEAN = 16; private static final int VERSION_CODE_JELLY_BEAN_MR2 = 18; private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL = getBuildFingerprintAndDeviceSerial(); /** Hidden constructor to prevent instantiation. */ private PRNGFixes() { } /** * Applies all fixes. * * @throws SecurityException * if a fix is needed but could not be applied. */ public static void apply() { applyOpenSSLFix(); installLinuxPRNGSecureRandom(); } /** * Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the * fix is not needed. * * @throws SecurityException * if the fix is needed but could not be applied. */ private static void applyOpenSSLFix() throws SecurityException { if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN) || (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) { // No need to apply the fix return; } try { // Mix in the device- and invocation-specific seed. Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto").getMethod("RAND_seed", byte[].class) .invoke(null, generateSeed()); // Mix output of Linux PRNG into OpenSSL's PRNG int bytesRead = (Integer) Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto") .getMethod("RAND_load_file", String.class, long.class).invoke(null, "/dev/urandom", 1024); if (bytesRead != 1024) { throw new IOException("Unexpected number of bytes read from Linux PRNG: " + bytesRead); } } catch (Exception e) { throw new SecurityException("Failed to seed OpenSSL PRNG", e); } } /** * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the * default. Does nothing if the implementation is already the default or if * there is not need to install the implementation. * * @throws SecurityException * if the fix is needed but could not be applied. */ private static void installLinuxPRNGSecureRandom() throws SecurityException { if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) { // No need to apply the fix return; } // Install a Linux PRNG-based SecureRandom implementation as the // default, if not yet installed. Provider[] secureRandomProviders = Security.getProviders("SecureRandom.SHA1PRNG"); if ((secureRandomProviders == null) || (secureRandomProviders.length < 1) || (!LinuxPRNGSecureRandomProvider.class.equals(secureRandomProviders[0].getClass()))) { Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1); } // Assert that new SecureRandom() and // SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed // by the Linux PRNG-based SecureRandom implementation. SecureRandom rng1 = new SecureRandom(); if (!LinuxPRNGSecureRandomProvider.class.equals(rng1.getProvider().getClass())) { throw new SecurityException("new SecureRandom() backed by wrong Provider: " + rng1.getProvider().getClass()); } SecureRandom rng2; try { rng2 = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new SecurityException("SHA1PRNG not available", e); } if (!LinuxPRNGSecureRandomProvider.class.equals(rng2.getProvider().getClass())) { throw new SecurityException("SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong" + " Provider: " + rng2.getProvider().getClass()); } } /** * {@code Provider} of {@code SecureRandom} engines which pass through * all requests to the Linux PRNG. */ private static class LinuxPRNGSecureRandomProvider extends Provider { private static final long serialVersionUID = -6266241202554913759L; public LinuxPRNGSecureRandomProvider() { super("LinuxPRNG", 1.0, "A Linux-specific random number provider that uses" + " /dev/urandom"); // Although /dev/urandom is not a SHA-1 PRNG, some apps // explicitly request a SHA1PRNG SecureRandom and we thus need to // prevent them from getting the default implementation whose output // may have low entropy. put("SecureRandom.SHA1PRNG", LinuxPRNGSecureRandom.class.getName()); put("SecureRandom.SHA1PRNG ImplementedIn", "Software"); } } /** * {@link SecureRandomSpi} which passes all requests to the Linux PRNG * ({@code /dev/urandom}). */ public static class LinuxPRNGSecureRandom extends SecureRandomSpi { private static final long serialVersionUID = 8996012769968439505L; /* * IMPLEMENTATION NOTE: Requests to generate bytes and to mix in a seed * are passed through to the Linux PRNG (/dev/urandom). Instances of * this class seed themselves by mixing in the current time, PID, UID, * build fingerprint, and hardware serial number (where available) into * Linux PRNG. * * Concurrency: Read requests to the underlying Linux PRNG are * serialized (on sLock) to ensure that multiple threads do not get * duplicated PRNG output. */ private static final File URANDOM_FILE = new File("/dev/urandom"); private static final Object sLock = new Object(); /** * Input stream for reading from Linux PRNG or {@code null} if not yet * opened. * * @GuardedBy("sLock") */ private static DataInputStream sUrandomIn; /** * Output stream for writing to Linux PRNG or {@code null} if not yet * opened. * * @GuardedBy("sLock") */ private static OutputStream sUrandomOut; /** * Whether this engine instance has been seeded. This is needed because * each instance needs to seed itself if the client does not explicitly * seed it. */ private boolean mSeeded; @Override protected void engineSetSeed(byte[] bytes) { try { OutputStream out; synchronized (sLock) { out = getUrandomOutputStream(); } out.write(bytes); out.flush(); } catch (IOException e) { // On a small fraction of devices /dev/urandom is not writable. // Log and ignore. Log.w(PRNGFixes.class.getSimpleName(), "Failed to mix seed into " + URANDOM_FILE); } finally { mSeeded = true; } } @Override protected void engineNextBytes(byte[] bytes) { if (!mSeeded) { // Mix in the device- and invocation-specific seed. engineSetSeed(generateSeed()); } try { DataInputStream in; synchronized (sLock) { in = getUrandomInputStream(); } synchronized (in) { in.readFully(bytes); } } catch (IOException e) { throw new SecurityException("Failed to read from " + URANDOM_FILE, e); } } @Override protected byte[] engineGenerateSeed(int size) { byte[] seed = new byte[size]; engineNextBytes(seed); return seed; } private DataInputStream getUrandomInputStream() { synchronized (sLock) { if (sUrandomIn == null) { // NOTE: Consider inserting a BufferedInputStream between // DataInputStream and FileInputStream if you need higher // PRNG output performance and can live with future PRNG // output being pulled into this process prematurely. try { sUrandomIn = new DataInputStream(new FileInputStream(URANDOM_FILE)); } catch (IOException e) { throw new SecurityException("Failed to open " + URANDOM_FILE + " for reading", e); } } return sUrandomIn; } } private OutputStream getUrandomOutputStream() throws IOException { synchronized (sLock) { if (sUrandomOut == null) { sUrandomOut = new FileOutputStream(URANDOM_FILE); } return sUrandomOut; } } } /** * Generates a device- and invocation-specific seed to be mixed into the * Linux PRNG. */ private static byte[] generateSeed() { try { ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream(); DataOutputStream seedBufferOut = new DataOutputStream(seedBuffer); seedBufferOut.writeLong(System.currentTimeMillis()); seedBufferOut.writeLong(System.nanoTime()); seedBufferOut.writeInt(Process.myPid()); seedBufferOut.writeInt(Process.myUid()); seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL); seedBufferOut.close(); return seedBuffer.toByteArray(); } catch (IOException e) { throw new SecurityException("Failed to generate seed", e); } } private static byte[] getBuildFingerprintAndDeviceSerial() { StringBuilder result = new StringBuilder(); String fingerprint = Build.FINGERPRINT; if (fingerprint != null) { result.append(fingerprint); } String serial = Build.SERIAL; if (serial != null) { result.append(serial); } try { return result.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 encoding not supported"); } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/PRNGFixes.java
Java
gpl3
11,817
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import android.util.Log; /** * * @author Nils Braden */ public class FileUtils { protected static final String TAG = FileUtils.class.getSimpleName(); /** * Supported extensions of imagefiles, see http://developer.android.com/guide/appendix/media-formats.html */ public static final String[] IMAGE_EXTENSIONS = { "jpeg", "jpg", "gif", "png", "bmp", "webp" }; public static final String IMAGE_MIME = "image/*"; /** * Supported extensions of audiofiles, see http://developer.android.com/guide/appendix/media-formats.html * I removed the extensions from this list which are also used for video files. It is easier to open these in the * videoplayer and blaming the source instead of trying to figure out mime-types by hand. */ public static final String[] AUDIO_EXTENSIONS = { "mp3", "mid", "midi", "xmf", "mxmf", "ogg", "wav" }; public static final String AUDIO_MIME = "audio/*"; /** * Supported extensions of videofiles, see http://developer.android.com/guide/appendix/media-formats.html */ public static final String[] VIDEO_EXTENSIONS = { "3gp", "mp4", "m4a", "aac", "ts", "webm", "mkv", "mpg", "mpeg", "avi", "flv" }; public static final String VIDEO_MIME = "video/*"; /** * Path on sdcard to store files (DB, Certificates, ...) */ public static final String SDCARD_PATH_FILES = "/Android/data/org.ttrssreader/files/"; /** * Path on sdcard to store cache */ public static final String SDCARD_PATH_CACHE = "/Android/data/org.ttrssreader/cache/"; /** * Downloads a given URL directly to a file, when maxSize bytes are reached the download is stopped and the file is * deleted. * * @param downloadUrl * the URL of the file * @param file * the destination file * @param maxSize * the size in bytes after which to abort the download * @param minSize * the minimum size in bytes after which to start the download * * @return length of downloaded file or negated file length if it exceeds {@code maxSize} or downloaded with errors. * So, if returned value less or equals to 0, then the file was not cached. */ public static long downloadToFile(String downloadUrl, File file, long maxSize, long minSize) { FileOutputStream fos = null; long byteWritten = 0l; boolean error = false; try { if (file.exists() && file.length() > 0l) { byteWritten = file.length(); } else { URL url = new URL(downloadUrl); URLConnection connection = url.openConnection(); connection.setConnectTimeout((int) (Utils.SECOND * 2)); connection.setReadTimeout((int) Utils.SECOND); // Check filesize if available from header try { long length = Long.parseLong(connection.getHeaderField("Content-Length")); if (length <= 0) { byteWritten = length; Log.w(TAG, "Content-Length equals 0 or is negative: " + length); } else if (length < minSize) { error = true; byteWritten = -length; Log.i(TAG, String.format( "Not starting download of %s, the size (%s bytes) is less then the minimum filesize of %s bytes.", downloadUrl, length, minSize)); } else if (length > maxSize) { error = true; byteWritten = -length; Log.i(TAG, String.format( "Not starting download of %s, the size (%s bytes) exceeds the maximum filesize of %s bytes.", downloadUrl, length, maxSize)); } } catch (Exception e) { Log.w(TAG, "Couldn't read Content-Length from url: " + downloadUrl); } if (byteWritten == 0l) { file.createNewFile(); fos = new FileOutputStream(file); InputStream is = connection.getInputStream(); int size = (int) Utils.KB * 8; byte[] buf = new byte[size]; int byteRead; while (((byteRead = is.read(buf)) != -1)) { fos.write(buf, 0, byteRead); byteWritten += byteRead; if (byteWritten > maxSize) { Log.w(TAG, String .format("Download interrupted, the size of %s bytes exceeds maximum filesize.", byteWritten)); // file length should be negated if file size exceeds {@code maxSize} error = true; byteWritten = -byteWritten; break; } } } } } catch (Exception e) { Log.e(TAG, "Download not finished properly. Exception: " + e.getMessage(), e); byteWritten = -file.length(); } finally { if (byteWritten <= 0) error = true; if (fos != null) { try { fos.close(); } catch (IOException e) { } } } if (error) Log.e(TAG, String.format("Stopped download from url '%s'. Downloaded %d bytes", downloadUrl, byteWritten)); else Log.e(TAG, String.format("Download from '%s' finished. Downloaded %d bytes", downloadUrl, byteWritten)); if (error && file.exists()) file.delete(); return byteWritten; } /** * At the moment this method just returns a generic mime-type for audio, video or image-files, a more specific way * of probing for the type (MIME-Sniffing or exact checks on the extension) are yet to be implemented. * * Implementation-Hint: See * https://code.google.com/p/openintents/source/browse/trunk/filemanager/FileManager/src/org * /openintents/filemanager/FileManagerActivity.java * * @param fileName * @return */ public static String getMimeType(String fileName) { String ret = ""; if (fileName == null || fileName.length() == 0) return ret; for (String ext : IMAGE_EXTENSIONS) { if (fileName.endsWith(ext)) return IMAGE_MIME; } for (String ext : AUDIO_EXTENSIONS) { if (fileName.endsWith(ext)) return AUDIO_MIME; } for (String ext : VIDEO_EXTENSIONS) { if (fileName.endsWith(ext)) return VIDEO_MIME; } return ret; } /** * group given files (URLs) into hash by mime-type * * @param attachments * collection of file names (URLs) * * @return map, which keys are found mime-types and values are file collections of this mime-type */ public static Map<String, Collection<String>> groupFilesByMimeType(Collection<String> attachments) { Map<String, Collection<String>> attachmentsByMimeType = new HashMap<String, Collection<String>>(); for (String url : attachments) { String mimeType = getMimeType(url); if (mimeType.length() > 0) { Collection<String> mimeTypeList = attachmentsByMimeType.get(mimeType); if (mimeTypeList == null) { mimeTypeList = new ArrayList<String>(); attachmentsByMimeType.put(mimeType, mimeTypeList); } mimeTypeList.add(url); } } return attachmentsByMimeType; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/FileUtils.java
Java
gpl3
9,267
package org.ttrssreader.utils; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Set; import android.net.Uri; import android.text.TextUtils; // contains code from the Apache Software foundation public class StringSupport { /** * Turns a camel case string into an underscored one, e.g. "HelloWorld" * becomes "hello_world". * * @param camelCaseString * the string to underscore * @return the underscored string */ protected static String underscore(String camelCaseString) { String[] words = splitByCharacterTypeCamelCase(camelCaseString); return TextUtils.join("_", words).toLowerCase(Locale.getDefault()); } /** * <p> * Splits a String by Character type as returned by <code>java.lang.Character.getType(char)</code>. Groups of * contiguous characters of the same type are returned as complete tokens, with the following exception: the * character of type <code>Character.UPPERCASE_LETTER</code>, if any, immediately preceding a token of type * <code>Character.LOWERCASE_LETTER</code> will belong to the following token rather than to the preceding, if any, * <code>Character.UPPERCASE_LETTER</code> token. * * <pre> * StringUtils.splitByCharacterTypeCamelCase(null) = null * StringUtils.splitByCharacterTypeCamelCase("") = [] * StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"] * StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"] * StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"] * StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"] * StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"] * StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"] * StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"] * </pre> * * @param str * the String to split, may be <code>null</code> * @return an array of parsed Strings, <code>null</code> if null String * input * @since 2.4 */ private static String[] splitByCharacterTypeCamelCase(String str) { return splitByCharacterType(str, true); } /** * <p> * Splits a String by Character type as returned by <code>java.lang.Character.getType(char)</code>. Groups of * contiguous characters of the same type are returned as complete tokens, with the following exception: if * <code>camelCase</code> is <code>true</code>, the character of type <code>Character.UPPERCASE_LETTER</code>, if * any, immediately preceding a token of type <code>Character.LOWERCASE_LETTER</code> will belong to the following * token rather than to the preceding, if any, <code>Character.UPPERCASE_LETTER</code> token. * * @param str * the String to split, may be <code>null</code> * @param camelCase * whether to use so-called "camel-case" for letter types * @return an array of parsed Strings, <code>null</code> if null String * input * @since 2.4 */ private static String[] splitByCharacterType(String str, boolean camelCase) { if (str == null) { return null; } if (str.length() == 0) { return new String[0]; } char[] c = str.toCharArray(); ArrayList<String> list = new ArrayList<String>(); int tokenStart = 0; int currentType = Character.getType(c[tokenStart]); for (int pos = tokenStart + 1; pos < c.length; pos++) { int type = Character.getType(c[pos]); if (type == currentType) { continue; } if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) { int newTokenStart = pos - 1; if (newTokenStart != tokenStart) { list.add(new String(c, tokenStart, newTokenStart - tokenStart)); tokenStart = newTokenStart; } } else { list.add(new String(c, tokenStart, pos - tokenStart)); tokenStart = pos; } currentType = type; } list.add(new String(c, tokenStart, c.length - tokenStart)); return (String[]) list.toArray(new String[list.size()]); } /** * Splits the ids into Sets of Strings with maxCount ids each. * * @param ids * the set of ids to be split * @param maxCount * the maximum length of each list * @return a set of Strings with comma-separated ids */ public static <T> Set<String> convertListToString(Collection<T> values, int maxCount) { Set<String> ret = new HashSet<String>(); if (values == null || values.isEmpty()) return ret; StringBuilder sb = new StringBuilder(); int count = 0; Iterator<T> it = values.iterator(); while (it.hasNext()) { Object o = it.next(); if (o == null) continue; sb.append(o); if (count == maxCount) { ret.add(sb.substring(0, sb.length() - 1)); sb = new StringBuilder(); count = 0; } else { sb.append(","); count++; } } if (sb.length() > 0) ret.add(sb.substring(0, sb.length() - 1)); return ret; } public static String[] setToArray(Set<String> set) { String[] ret = new String[set.size()]; int i = 0; for (String s : set) { ret[i++] = s; } return ret; } public static String getBaseURL(String url) { Uri uri = Uri.parse(url); if (uri != null) { return uri.getScheme() + "://" + uri.getAuthority(); } return null; } public static String convertStreamToString(InputStream inputStream) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = new BufferedInputStream(inputStream, (int) Utils.KB); byte[] buffer = new byte[(int) Utils.KB]; int n = 0; try { while (-1 != (n = in.read(buffer))) { out.write(buffer, 0, n); } } finally { out.close(); in.close(); } return out.toString("UTF-8"); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/StringSupport.java
Java
gpl3
6,958
package org.ttrssreader.utils; import java.lang.ref.WeakReference; import android.os.Handler; import android.os.Message; /** * Source: http://stackoverflow.com/a/13493726 (User: Timmmm)<br> * A handler which keeps a weak reference to a fragment. According to * Android's lint, references to Handlers can be kept around for a long * time - longer than Fragments for example. So we should use handlers * that don't have strong references to the things they are handling for. * * You can use this class to more or less forget about that requirement. * Unfortunately you can have anonymous static inner classes, so it is a * little more verbose. * * Example use: * * private static class MsgHandler extends WeakReferenceHandler<MyFragment> * { * public MsgHandler(MyFragment fragment) { super(fragment); } * * @Override * public void handleMessage(MyFragment fragment, Message msg) * { * fragment.doStuff(msg.arg1); * } * } * * // ... * MsgHandler handler = new MsgHandler(this); */ public abstract class WeakReferenceHandler<T> extends Handler { private WeakReference<T> mReference; public WeakReferenceHandler(T reference) { mReference = new WeakReference<T>(reference); } @Override public void handleMessage(Message msg) { if (mReference.get() == null) return; handleMessage(mReference.get(), msg); } protected abstract void handleMessage(T reference, Message msg); }
025003b-rss
ttrss-reader/src/org/ttrssreader/utils/WeakReferenceHandler.java
Java
gpl3
1,549
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.json.JSONException; import org.json.JSONObject; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.Data; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.pojos.Label; import org.ttrssreader.utils.Base64; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.content.Context; import android.util.Log; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.MalformedJsonException; public abstract class JSONConnector { protected static final String TAG = JSONConnector.class.getSimpleName(); protected static String lastError = ""; protected static boolean hasLastError = false; protected static final String PARAM_OP = "op"; protected static final String PARAM_USER = "user"; protected static final String PARAM_PW = "password"; protected static final String PARAM_CAT_ID = "cat_id"; protected static final String PARAM_CATEGORY_ID = "category_id"; protected static final String PARAM_FEED_ID = "feed_id"; protected static final String PARAM_FEED_URL = "feed_url"; protected static final String PARAM_ARTICLE_ID = "article_id"; protected static final String PARAM_ARTICLE_IDS = "article_ids"; protected static final String PARAM_LIMIT = "limit"; protected static final int PARAM_LIMIT_API_5 = 60; public static final int PARAM_LIMIT_MAX_VALUE = 200; protected static final String PARAM_VIEWMODE = "view_mode"; protected static final String PARAM_ORDERBY = "order_by"; protected static final String PARAM_SHOW_CONTENT = "show_content"; protected static final String PARAM_INC_ATTACHMENTS = "include_attachments"; // include_attachments available since // 1.5.3 but is ignored on older // versions protected static final String PARAM_SINCE_ID = "since_id"; protected static final String PARAM_SEARCH = "search"; protected static final String PARAM_SKIP = "skip"; protected static final String PARAM_MODE = "mode"; protected static final String PARAM_FIELD = "field"; // 0-starred, 1-published, 2-unread, 3-article note (since api // level 1) protected static final String PARAM_DATA = "data"; // optional data parameter when setting note field protected static final String PARAM_IS_CAT = "is_cat"; protected static final String PARAM_PREF = "pref_name"; protected static final String PARAM_OUTPUT_MODE = "output_mode"; // output_mode (default: flc) - what kind of // information to return (f-feeds, l-labels, // c-categories, t-tags) protected static final String VALUE_LOGIN = "login"; protected static final String VALUE_GET_CATEGORIES = "getCategories"; protected static final String VALUE_GET_FEEDS = "getFeeds"; protected static final String VALUE_GET_HEADLINES = "getHeadlines"; protected static final String VALUE_UPDATE_ARTICLE = "updateArticle"; protected static final String VALUE_CATCHUP = "catchupFeed"; protected static final String VALUE_UPDATE_FEED = "updateFeed"; protected static final String VALUE_GET_PREF = "getPref"; protected static final String VALUE_GET_VERSION = "getVersion"; protected static final String VALUE_GET_LABELS = "getLabels"; protected static final String VALUE_SET_LABELS = "setArticleLabel"; protected static final String VALUE_SHARE_TO_PUBLISHED = "shareToPublished"; protected static final String VALUE_FEED_SUBSCRIBE = "subscribeToFeed"; protected static final String VALUE_FEED_UNSUBSCRIBE = "unsubscribeFeed"; protected static final String VALUE_LABEL_ID = "label_id"; protected static final String VALUE_ASSIGN = "assign"; protected static final String VALUE_API_LEVEL = "getApiLevel"; protected static final String VALUE_OUTPUT_MODE = "flc"; // f - feeds, l - labels, c - categories, t - tags protected static final String ERROR = "error"; protected static final String NOT_LOGGED_IN = "NOT_LOGGED_IN"; protected static final String UNKNOWN_METHOD = "UNKNOWN_METHOD"; protected static final String NOT_LOGGED_IN_MESSAGE = "Couldn't login to your account, please check your credentials."; protected static final String API_DISABLED = "API_DISABLED"; protected static final String API_DISABLED_MESSAGE = "Please enable API for the user \"%s\" in the preferences of this user on the Server."; protected static final String STATUS = "status"; protected static final String API_LEVEL = "api_level"; protected static final String SESSION_ID = "session_id"; // session id as an OUT parameter protected static final String SID = "sid"; // session id as an IN parameter protected static final String ID = "id"; public static final String TITLE = "title"; public static final String UNREAD = "unread"; protected static final String CAT_ID = "cat_id"; public static final String FEED_ID = "feed_id"; public static final String UPDATED = "updated"; public static final String CONTENT = "content"; public static final String URL = "link"; protected static final String URL_SHARE = "url"; protected static final String FEED_URL = "feed_url"; public static final String COMMENT_URL = "comments"; public static final String ATTACHMENTS = "attachments"; protected static final String CONTENT_URL = "content_url"; public static final String STARRED = "marked"; public static final String PUBLISHED = "published"; protected static final String VALUE = "value"; protected static final String VERSION = "version"; protected static final String LEVEL = "level"; protected static final String CAPTION = "caption"; protected static final String CHECKED = "checked"; protected static final String COUNTER_KIND = "kind"; protected static final String COUNTER_CAT = "cat"; protected static final String COUNTER_ID = "id"; protected static final String COUNTER_COUNTER = "counter"; protected static final int MAX_ID_LIST_LENGTH = 100; protected boolean httpAuth = false; protected String httpUsername; protected String httpPassword; protected String sessionId = null; protected final Object lock = new Object(); protected Context context; private int apiLevel = -1; public JSONConnector(Context context) { refreshHTTPAuth(); this.context = context; } protected abstract InputStream doRequest(Map<String, String> params); protected void refreshHTTPAuth() { httpAuth = Controller.getInstance().useHttpAuth(); if (!httpAuth) return; if (httpUsername != null && httpUsername.equals(Controller.getInstance().httpUsername())) return; if (httpPassword != null && httpPassword.equals(Controller.getInstance().httpPassword())) return; // Refresh data httpUsername = Controller.getInstance().httpUsername(); httpPassword = Controller.getInstance().httpPassword(); } protected void logRequest(final JSONObject json) throws JSONException { // Filter password and session-id Object paramPw = json.remove(PARAM_PW); Object paramSID = json.remove(SID); Log.i(TAG, json.toString()); json.put(PARAM_PW, paramPw); json.put(SID, paramSID); } private String readResult(Map<String, String> params, boolean login) throws IOException { return readResult(params, login, true); } private String readResult(Map<String, String> params, boolean login, boolean retry) throws IOException { InputStream in = doRequest(params); if (in == null) return null; JsonReader reader = null; String ret = ""; try { reader = new JsonReader(new InputStreamReader(in, "UTF-8")); // Check if content contains array or object, array indicates login-response or error, object is content reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("content")) { JsonToken t = reader.peek(); if (t.equals(JsonToken.BEGIN_OBJECT)) { JsonObject object = new JsonObject(); reader.beginObject(); while (reader.hasNext()) { object.addProperty(reader.nextName(), reader.nextString()); } reader.endObject(); if (object.get(SESSION_ID) != null) { ret = object.get(SESSION_ID).getAsString(); } if (object.get(STATUS) != null) { ret = object.get(STATUS).getAsString(); } if (object.get(API_LEVEL) != null) { this.apiLevel = object.get(API_LEVEL).getAsInt(); } if (object.get(VALUE) != null) { ret = object.get(VALUE).getAsString(); } if (object.get(ERROR) != null) { String message = object.get(ERROR).getAsString(); if (message.contains(NOT_LOGGED_IN)) { if (!login && retry && login()) { return readResult(params, false, false); // Just do the same request again } else { hasLastError = true; lastError = message; return null; } } if (message.contains(API_DISABLED)) { hasLastError = true; lastError = String.format(API_DISABLED_MESSAGE, Controller.getInstance().username()); return null; } // Any other error hasLastError = true; lastError = message; return null; } } } else { reader.skipValue(); } } } finally { if (reader != null) reader.close(); } if (ret.startsWith("\"")) ret = ret.substring(1, ret.length()); if (ret.endsWith("\"")) ret = ret.substring(0, ret.length() - 1); return ret; } private JsonReader prepareReader(Map<String, String> params) throws IOException { return prepareReader(params, true); } private JsonReader prepareReader(Map<String, String> params, boolean firstCall) throws IOException { InputStream in = doRequest(params); if (in == null) return null; JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); // Check if content contains array or object, array indicates login-response or error, object is content try { reader.beginObject(); } catch (Exception e) { e.printStackTrace(); return null; } while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("content")) { JsonToken t = reader.peek(); if (t.equals(JsonToken.BEGIN_ARRAY)) { return reader; } else if (t.equals(JsonToken.BEGIN_OBJECT)) { JsonObject object = new JsonObject(); reader.beginObject(); String nextName = reader.nextName(); // We have a BEGIN_OBJECT here but its just the response to call "subscribeToFeed" if ("status".equals(nextName)) return reader; // Handle error while (reader.hasNext()) { if (nextName != null) { object.addProperty(nextName, reader.nextString()); nextName = null; } else { object.addProperty(reader.nextName(), reader.nextString()); } } reader.endObject(); if (object.get(ERROR) != null) { String message = object.get(ERROR).toString(); if (message.contains(NOT_LOGGED_IN)) { lastError = NOT_LOGGED_IN; if (firstCall && login() && !hasLastError) return prepareReader(params, false); // Just do the same request again else return null; } if (message.contains(API_DISABLED)) { hasLastError = true; lastError = String.format(API_DISABLED_MESSAGE, Controller.getInstance().username()); return null; } // Any other error hasLastError = true; lastError = message; } } } else { reader.skipValue(); } } return null; } public boolean sessionAlive() { // Make sure we are logged in if (sessionId == null || lastError.equals(NOT_LOGGED_IN)) if (!login()) return false; if (hasLastError) return false; return true; } /** * Does an API-Call and ignores the result. * * @param params * @return true if the call was successful. */ private boolean doRequestNoAnswer(Map<String, String> params) { if (!sessionAlive()) return false; try { String result = readResult(params, false); // Reset error, this is only for an api-bug which returns an empty result for updateFeed if (result == null) pullLastError(); if ("OK".equals(result)) return true; else return false; } catch (MalformedJsonException mje) { // Reset error, this is only for an api-bug which returns an empty result for updateFeed pullLastError(); } catch (IOException e) { e.printStackTrace(); if (!hasLastError) { hasLastError = true; lastError = formatException(e); } } return false; } /** * Tries to login to the ttrss-server with the base64-encoded password. * * @return true on success, false otherwise */ private boolean login() { long time = System.currentTimeMillis(); // Just login once, check if already logged in after acquiring the lock on mSessionId if (sessionId != null && !lastError.equals(NOT_LOGGED_IN)) return true; synchronized (lock) { if (sessionId != null && !lastError.equals(NOT_LOGGED_IN)) return true; // Login done while we were waiting for the lock Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_LOGIN); params.put(PARAM_USER, Controller.getInstance().username()); params.put(PARAM_PW, Base64.encodeBytes(Controller.getInstance().password().getBytes())); try { sessionId = readResult(params, true, false); if (sessionId != null) { Log.d(TAG, "login: " + (System.currentTimeMillis() - time) + "ms"); return true; } } catch (IOException e) { e.printStackTrace(); if (!hasLastError) { hasLastError = true; lastError = formatException(e); } } if (!hasLastError) { // Login didnt succeed, write message hasLastError = true; lastError = NOT_LOGGED_IN_MESSAGE; } return false; } } // ***************** Helper-Methods ************************************************** private Set<String> parseAttachments(JsonReader reader) throws IOException { Set<String> ret = new HashSet<String>(); reader.beginArray(); while (reader.hasNext()) { String attId = null; String attUrl = null; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(CONTENT_URL)) { attUrl = reader.nextString(); } else if (name.equals(ID)) { attId = reader.nextString(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); if (attId != null && attUrl != null) ret.add(attUrl); } reader.endArray(); return ret; } /** * parse articles from JSON-reader * * @param articles * container, where parsed articles will be stored * @param reader * JSON-reader, containing articles (received from server) * @param labelId * ID of label to be added to each parsed article * @param skipNames * set of names (article properties), which should not be processed (may be {@code null}) * @param filter * filter for articles, defining which articles should be omitted while parsing (may be {@code null}) * @return amount of processed articles */ private int parseArticleArray(final Set<Article> articles, JsonReader reader, long labelId, Set<Article.ArticleField> skipNames, IArticleOmitter filter) { long time = System.currentTimeMillis(); int count = 0; try { reader.beginArray(); while (reader.hasNext()) { Article a = new Article(); boolean skipObject = false; reader.beginObject(); while (reader.hasNext() && reader.peek().equals(JsonToken.NAME)) { if (skipObject) { // field name reader.skipValue(); // field value reader.skipValue(); continue; } String name = reader.nextName(); try { Article.ArticleField field = Article.ArticleField.valueOf(name); if (skipNames != null && skipNames.contains(field)) { reader.skipValue(); continue; } switch (field) { case id: a.id = reader.nextInt(); break; case title: a.title = reader.nextString(); break; case unread: a.isUnread = reader.nextBoolean(); break; case updated: a.updated = new Date(reader.nextLong() * 1000); break; case feed_id: if (reader.peek() == JsonToken.NULL) reader.nextNull(); else a.feedId = reader.nextInt(); break; case content: a.content = reader.nextString(); break; case link: a.url = reader.nextString(); break; case comments: a.commentUrl = reader.nextString(); break; case attachments: a.attachments = parseAttachments(reader); break; case marked: a.isStarred = reader.nextBoolean(); break; case published: a.isPublished = reader.nextBoolean(); break; case labels: a.labels = parseLabels(reader); break; case author: a.author = reader.nextString(); break; // valid, but currently unused // TODO: incorporate into Article object? case is_updated: case tags: case feed_title: case comments_count: case comments_link: case always_display_attachments: case score: case note: case lang: reader.skipValue(); continue; } if (filter != null) skipObject = filter.omitArticle(field, a); } catch (IllegalArgumentException e) { Log.w(TAG, "Result contained illegal value for entry \"" + name + "\"."); reader.skipValue(); continue; } } reader.endObject(); if (!skipObject && a.id != -1 && a.title != null) { articles.add(a); } count++; } reader.endArray(); } catch (StopJsonParsingException e) { Log.i(TAG, "Parsing of aricle array was broken after " + count + " articles"); } catch (OutOfMemoryError e) { Controller.getInstance().lowMemory(true); // Low memory detected } catch (Exception e) { Log.e(TAG, "Input data could not be read: " + e.getMessage() + " (" + e.getCause() + ")", e); } Log.d(TAG, "parseArticleArray: parsing " + count + " articles took " + (System.currentTimeMillis() - time) + "ms"); return count; } private Set<Label> parseLabels(final JsonReader reader) throws IOException { Set<Label> ret = new HashSet<Label>(); if (reader.peek().equals(JsonToken.BEGIN_ARRAY)) { reader.beginArray(); } else { reader.skipValue(); return ret; } try { while (reader.hasNext()) { Label label = new Label(); reader.beginArray(); try { label.id = Integer.parseInt(reader.nextString()); label.caption = reader.nextString(); label.foregroundColor = reader.nextString(); label.backgroundColor = reader.nextString(); label.checked = true; } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } ret.add(label); reader.endArray(); } reader.endArray(); } catch (Exception e) { // Ignore exceptions here try { if (reader.peek().equals(JsonToken.END_ARRAY)) reader.endArray(); } catch (Exception ee) { } } return ret; } // ***************** Retrieve-Data-Methods ************************************************** /** * Retrieves all categories. * * @return a list of categories. */ public Set<Category> getCategories() { long time = System.currentTimeMillis(); Set<Category> ret = new LinkedHashSet<Category>(); if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_CATEGORIES); JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { int id = -1; String title = null; int unread = 0; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(ID)) { id = reader.nextInt(); } else if (name.equals(TITLE)) { title = reader.nextString(); } else if (name.equals(UNREAD)) { unread = reader.nextInt(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); // Don't handle categories with an id below 1, we already have them in the DB from // Data.updateVirtualCategories() if (id > 0 && title != null) ret.add(new Category(id, title, unread)); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } Log.d(TAG, "getCategories: " + (System.currentTimeMillis() - time) + "ms"); return ret; } /** * get current feeds from server * * @param tolerateWrongUnreadInformation * if set to {@code false}, then * lazy server will be updated before * * @return set of actual feeds on server */ private Set<Feed> getFeeds(boolean tolerateWrongUnreadInformation) { long time = System.currentTimeMillis(); Set<Feed> ret = new LinkedHashSet<Feed>(); if (!sessionAlive()) return ret; if (!tolerateWrongUnreadInformation) { makeLazyServerWork(); } Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_FEEDS); params.put(PARAM_CAT_ID, Data.VCAT_ALL + ""); // Hardcoded -4 fetches all feeds. See // http://tt-rss.org/redmine/wiki/tt-rss/JsonApiReference#getFeeds JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { int categoryId = -1; int id = 0; String title = null; String feedUrl = null; int unread = 0; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(ID)) { id = reader.nextInt(); } else if (name.equals(CAT_ID)) { categoryId = reader.nextInt(); } else if (name.equals(TITLE)) { title = reader.nextString(); } else if (name.equals(FEED_URL)) { feedUrl = reader.nextString(); } else if (name.equals(UNREAD)) { unread = reader.nextInt(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); if (id != -1 || categoryId == -2) // normal feed (>0) or label (-2) if (title != null) // Dont like complicated if-statements.. ret.add(new Feed(id, categoryId, title, feedUrl, unread)); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } Log.d(TAG, "getFeeds: " + (System.currentTimeMillis() - time) + "ms"); return ret; } /** * Retrieves all feeds from server. * * @return a set of all feeds on server. */ public Set<Feed> getFeeds() { return getFeeds(false); } private boolean makeLazyServerWork(Integer feedId) { if (Controller.getInstance().lazyServer()) { Map<String, String> taskParams = new HashMap<String, String>(); taskParams.put(PARAM_OP, VALUE_UPDATE_FEED); taskParams.put(PARAM_FEED_ID, String.valueOf(feedId)); return doRequestNoAnswer(taskParams); } return true; } private long noTaskUntil = 0; final static private long minTaskIntervall = 10 * Utils.MINUTE; private boolean makeLazyServerWork() { boolean ret = true; final long time = System.currentTimeMillis(); if (Controller.getInstance().lazyServer() && (noTaskUntil < time)) { noTaskUntil = time + minTaskIntervall; Set<Feed> feedset = getFeeds(true); Iterator<Feed> feeds = feedset.iterator(); while (feeds.hasNext()) { final Feed f = feeds.next(); ret = ret && makeLazyServerWork(f.id); } } return ret; } /** * @see #getHeadlines(Integer, int, String, boolean, int, int) */ public void getHeadlines(final Set<Article> articles, Integer id, int limit, String viewMode, boolean isCategory) { getHeadlines(articles, id, limit, viewMode, isCategory, 0); } /** * @see #getHeadlines(Integer, int, String, boolean, int, int) */ public void getHeadlines(final Set<Article> articles, Integer id, int limit, String viewMode, boolean isCategory, int sinceId) { getHeadlines(articles, id, limit, viewMode, isCategory, sinceId, null, null, new IdUpdatedArticleOmitter(null, null)); } /** * Retrieves the specified articles. * * @param articles * container for retrieved articles * @param id * the id of the feed/category * @param limit * the maximum number of articles to be fetched * @param viewMode * indicates wether only unread articles should be included (Possible values: all_articles, unread, * adaptive, marked, updated) * @param isCategory * indicates if we are dealing with a category or a feed * @param sinceId * the first ArticleId which is to be retrieved. * @param search * search query * @param skipProperties * set of article fields, which should not be parsed (may be {@code null}) * @param filter * filter for articles, defining which articles should be omitted while parsing (may be {@code null}) */ public void getHeadlines(final Set<Article> articles, Integer id, int limit, String viewMode, boolean isCategory, Integer sinceId, String search, Set<Article.ArticleField> skipProperties, IArticleOmitter filter) { long time = System.currentTimeMillis(); int offset = 0; int count = 0; int maxSize = articles.size() + limit; if (!sessionAlive()) return; int limitParam = Math.min((apiLevel < 6) ? PARAM_LIMIT_API_5 : PARAM_LIMIT_MAX_VALUE, limit); makeLazyServerWork(id); while (articles.size() < maxSize) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_HEADLINES); params.put(PARAM_FEED_ID, id + ""); params.put(PARAM_LIMIT, limitParam + ""); params.put(PARAM_SKIP, offset + ""); params.put(PARAM_VIEWMODE, viewMode); // params.put(PARAM_ORDERBY, "feed_dates"); if (skipProperties == null || !skipProperties.contains(Article.ArticleField.content)) params.put(PARAM_SHOW_CONTENT, "1"); if (skipProperties == null || !skipProperties.contains(Article.ArticleField.attachments)) params.put(PARAM_INC_ATTACHMENTS, "1"); params.put(PARAM_IS_CAT, (isCategory ? "1" : "0")); if (sinceId > 0) params.put(PARAM_SINCE_ID, sinceId + ""); if (search != null) params.put(PARAM_SEARCH, search); JsonReader reader = null; try { reader = prepareReader(params); if (hasLastError) return; if (reader == null) continue; count = parseArticleArray(articles, reader, (!isCategory && id < -10 ? id : -1), skipProperties, filter); if (count < limitParam) break; else offset += count; } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } Log.d(TAG, "getHeadlines: " + (System.currentTimeMillis() - time) + "ms"); } /** * Marks the given list of article-Ids as read/unread depending on int articleState. * * @param articlesIds * a list of article-ids. * @param articleState * the new state of the article (0 -> mark as read; 1 -> mark as unread). */ public boolean setArticleRead(Set<Integer> articlesIds, int articleState) { boolean ret = true; if (articlesIds.isEmpty()) return ret; for (String idList : StringSupport.convertListToString(articlesIds, MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "2"); ret = ret && doRequestNoAnswer(params); } return ret; } /** * Marks the given Article as "starred"/"not starred" depending on int articleState. * * @param ids * a list of article-ids. * @param articleState * the new state of the article (0 -> not starred; 1 -> starred; 2 -> toggle). * @return true if the operation succeeded. */ public boolean setArticleStarred(Set<Integer> ids, int articleState) { boolean ret = true; if (ids.size() == 0) return ret; for (String idList : StringSupport.convertListToString(ids, MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "0"); ret = ret && doRequestNoAnswer(params); } return ret; } /** * Marks the given Articles as "published"/"not published" depending on articleState. * * @param ids * a list of article-ids with corresponding notes (may be null). * @param articleState * the new state of the articles (0 -> not published; 1 -> published; 2 -> toggle). * @return true if the operation succeeded. */ public boolean setArticlePublished(Map<Integer, String> ids, int articleState) { boolean ret = true; if (ids.size() == 0) return ret; for (String idList : StringSupport.convertListToString(ids.keySet(), MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "1"); ret = ret && doRequestNoAnswer(params); // Add a note to the article(s) for (Integer id : ids.keySet()) { String note = ids.get(id); if (note == null || note.equals("")) continue; params.put(PARAM_FIELD, "3"); // Field 3 is the "Add note" field params.put(PARAM_DATA, note); ret = ret && doRequestNoAnswer(params); } } return ret; } /** * Marks a feed or a category with all its feeds as read. * * @param id * the feed-id/category-id. * @param isCategory * indicates whether id refers to a feed or a category. * @return true if the operation succeeded. */ public boolean setRead(int id, boolean isCategory) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_CATCHUP); params.put(PARAM_FEED_ID, id + ""); params.put(PARAM_IS_CAT, (isCategory ? "1" : "0")); return doRequestNoAnswer(params); } public boolean feedUnsubscribe(int feed_id) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_FEED_UNSUBSCRIBE); params.put(PARAM_FEED_ID, feed_id + ""); return doRequestNoAnswer(params); } /** * Returns the value for the given preference-name as a string. * * @param pref * the preferences name * @return the value of the preference or null if it ist not set or unknown */ public String getPref(String pref) { if (!sessionAlive()) return null; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_PREF); params.put(PARAM_PREF, pref); try { String ret = readResult(params, false); return ret; } catch (IOException e) { e.printStackTrace(); } return null; } /** * Returns the version of the server-installation as integer (version-string without dots) * * @return the version */ public int getVersion() { int ret = -1; if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_VERSION); String response = ""; JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { try { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals(VERSION)) { response = reader.nextString(); } else { reader.skipValue(); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } } // Replace dots, parse integer ret = Integer.parseInt(response.replace(".", "")); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } return ret; } /** * Returns a Set of all existing labels. If some of the labels are checked for the given article the property * "checked" is true. * * @return a set of labels. */ public Set<Label> getLabels(Integer articleId) { Set<Label> ret = new HashSet<Label>(); if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_LABELS); params.put(PARAM_ARTICLE_ID, articleId.toString()); JsonReader reader = null; Label label = new Label(); try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { try { reader.beginObject(); label = new Label(); while (reader.hasNext()) { String name = reader.nextName(); if (ID.equals(name)) { label.id = reader.nextInt(); } else if (CAPTION.equals(name)) { label.caption = reader.nextString(); } else if (CHECKED.equals(name)) { label.checked = reader.nextBoolean(); } else { reader.skipValue(); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } } reader.endArray(); ret.add(label); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } return ret; } public boolean setArticleLabel(Set<Integer> articleIds, int labelId, boolean assign) { boolean ret = true; if (articleIds.size() == 0) return ret; for (String idList : StringSupport.convertListToString(articleIds, MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_SET_LABELS); params.put(PARAM_ARTICLE_IDS, idList); params.put(VALUE_LABEL_ID, labelId + ""); params.put(VALUE_ASSIGN, (assign ? "1" : "0")); ret = ret && doRequestNoAnswer(params); } return ret; } public boolean shareToPublished(String title, String url, String content) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_SHARE_TO_PUBLISHED); params.put(TITLE, title); params.put(URL_SHARE, url); params.put(CONTENT, content); return doRequestNoAnswer(params); } public class SubscriptionResponse { public int code = -1; public String message = null; } public SubscriptionResponse feedSubscribe(String feed_url, int category_id) { SubscriptionResponse ret = new SubscriptionResponse(); if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_FEED_SUBSCRIBE); params.put(PARAM_FEED_URL, feed_url); params.put(PARAM_CATEGORY_ID, category_id + ""); String code = ""; String message = null; JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("code")) { code = reader.nextString(); } else if (name.equals("message")) { message = reader.nextString(); } else { reader.skipValue(); } } if (!code.contains(UNKNOWN_METHOD)) { ret.code = Integer.parseInt(code); ret.message = message; } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } return ret; } /** * Returns true if there was an error. * * @return true if there was an error. */ public boolean hasLastError() { return hasLastError; } /** * Returns the last error-message and resets the error-state of the connector. * * @return a string with the last error-message. */ public String pullLastError() { String ret = new String(lastError); lastError = ""; hasLastError = false; return ret; } protected static String formatException(Exception e) { return e.getMessage() + (e.getCause() != null ? "(" + e.getCause() + ")" : ""); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/JSONConnector.java
Java
gpl3
50,535
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.SocketException; import java.util.Map; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import org.json.JSONObject; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.Utils; import android.content.Context; import android.util.Log; public class JavaJSONConnector extends JSONConnector { protected static final String TAG = JavaJSONConnector.class.getSimpleName(); public JavaJSONConnector(Context context) { super(context); } protected InputStream doRequest(Map<String, String> params) { try { if (sessionId != null) params.put(SID, sessionId); JSONObject json = new JSONObject(params); byte[] outputBytes = json.toString().getBytes("UTF-8"); logRequest(json); refreshHTTPAuth(); // Create Connection HttpURLConnection con = (HttpURLConnection) Controller.getInstance().url().openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Content-Length", Integer.toString(outputBytes.length)); int timeoutSocket = (int) ((Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND); con.setReadTimeout(timeoutSocket); con.setConnectTimeout((int) (8 * Utils.SECOND)); // Add POST data con.getOutputStream().write(outputBytes); // Try to check for HTTP Status codes int code = con.getResponseCode(); if (code >= 400 && code < 600) { hasLastError = true; lastError = "Server returned status: " + code + " (Message: " + con.getResponseMessage() + ")"; return null; } return con.getInputStream(); } catch (SSLPeerUnverifiedException e) { // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take // Not doing anything here since this error should happen only when no certificate is received from the // server. Log.w(TAG, "SSLPeerUnverifiedException in doRequest(): " + formatException(e)); } catch (SSLException e) { if ("No peer certificate".equals(e.getMessage())) { // Handle this by ignoring it, this occurrs very often when the connection is instable. Log.w(TAG, "SSLException in doRequest(): " + formatException(e)); } else { hasLastError = true; lastError = "SSLException in doRequest(): " + formatException(e); } } catch (InterruptedIOException e) { Log.w(TAG, "InterruptedIOException in doRequest(): " + formatException(e)); } catch (SocketException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(TAG, "SocketException in doRequest(): " + formatException(e)); } catch (Exception e) { hasLastError = true; lastError = "Exception in doRequest(): " + formatException(e); e.printStackTrace(); } return null; } @Override protected void refreshHTTPAuth() { super.refreshHTTPAuth(); if (!httpAuth) return; Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(httpUsername, httpPassword.toCharArray()); } }); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/JavaJSONConnector.java
Java
gpl3
4,807
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net.deprecated; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; public class FakeTrustManager implements X509TrustManager { private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return _AcceptedIssuers; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/deprecated/FakeTrustManager.java
Java
gpl3
1,225
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net.deprecated; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class FakeSocketFactory implements SocketFactory, LayeredSocketFactory { private SSLContext sslcontext = null; private static SSLContext createEasySSLContext() throws IOException { try { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new FakeTrustManager() }, null); return context; } catch (Exception e) { throw new IOException(e.getMessage()); } } private SSLContext getSSLContext() throws IOException { if (this.sslcontext == null) { this.sslcontext = createEasySSLContext(); } return this.sslcontext; } @Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; } @Override public Socket createSocket() throws IOException { return getSSLContext().getSocketFactory().createSocket(); } @Override public boolean isSecure(Socket arg0) throws IllegalArgumentException { return true; } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/deprecated/FakeSocketFactory.java
Java
gpl3
3,285
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net.deprecated; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.SocketException; import java.net.URISyntaxException; import java.util.Map; import java.util.zip.GZIPInputStream; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONObject; import org.ttrssreader.controllers.Controller; import org.ttrssreader.net.JSONConnector; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.Utils; import android.content.Context; import android.util.Log; public class ApacheJSONConnector extends JSONConnector { protected static final String TAG = ApacheJSONConnector.class.getSimpleName(); protected CredentialsProvider credProvider = null; protected DefaultHttpClient client; public ApacheJSONConnector(Context context) { super(context); } protected InputStream doRequest(Map<String, String> params) { HttpPost post = new HttpPost(); try { if (sessionId != null) params.put(SID, sessionId); // check if http-Auth-Settings have changed, reload values if necessary refreshHTTPAuth(); // Set Address post.setURI(Controller.getInstance().uri()); post.addHeader("Accept-Encoding", "gzip"); // Add POST data JSONObject json = new JSONObject(params); StringEntity jsonData = new StringEntity(json.toString(), "UTF-8"); jsonData.setContentType("application/json"); post.setEntity(jsonData); // Add timeouts for the connection { HttpParams httpParams = post.getParams(); // Set the timeout until a connection is established. int timeoutConnection = (int) (8 * Utils.SECOND); HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) which is the timeout for waiting for data. // use longer timeout when lazyServer-Feature is used int timeoutSocket = (int) ((Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND); HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); post.setParams(httpParams); } logRequest(json); if (client == null) client = HttpClientFactory.getInstance().getHttpClient(post.getParams()); else client.setParams(post.getParams()); // Add SSL-Stuff if (credProvider != null) client.setCredentialsProvider(credProvider); } catch (URISyntaxException e) { hasLastError = true; lastError = "Invalid URI."; return null; } catch (Exception e) { hasLastError = true; lastError = "Error creating HTTP-Connection in (old) doRequest(): " + formatException(e); e.printStackTrace(); return null; } HttpResponse response = null; try { response = client.execute(post); // Execute the request } catch (ClientProtocolException e) { hasLastError = true; lastError = "ClientProtocolException in (old) doRequest(): " + formatException(e); return null; } catch (SSLPeerUnverifiedException e) { // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take // Not doing anything here since this error should happen only when no certificate is received from the // server. Log.w(TAG, "SSLPeerUnverifiedException in (old) doRequest(): " + formatException(e)); return null; } catch (SSLException e) { if ("No peer certificate".equals(e.getMessage())) { // Handle this by ignoring it, this occurrs very often when the connection is instable. Log.w(TAG, "SSLException in (old) doRequest(): " + formatException(e)); } else { hasLastError = true; lastError = "SSLException in (old) doRequest(): " + formatException(e); } return null; } catch (InterruptedIOException e) { Log.w(TAG, "InterruptedIOException in (old) doRequest(): " + formatException(e)); return null; } catch (SocketException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(TAG, "SocketException in (old) doRequest(): " + formatException(e)); return null; } catch (Exception e) { hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } // Try to check for HTTP Status codes int code = response.getStatusLine().getStatusCode(); if (code >= 400 && code < 600) { hasLastError = true; lastError = "Server returned status: " + code; return null; } InputStream instream = null; try { HttpEntity entity = response.getEntity(); if (entity != null) instream = entity.getContent(); // Try to decode gzipped instream, if it is not gzip we stay to normal reading Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) instream = new GZIPInputStream(instream); // Header size = response.getFirstHeader("Api-Content-Length"); // Log.d(TAG, "SIZE: " + size.getValue()); if (instream == null) { hasLastError = true; lastError = "Couldn't get InputStream in (old) Method doRequest(String url) [instream was null]"; return null; } } catch (Exception e) { if (instream != null) try { instream.close(); } catch (IOException e1) { } hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } return instream; } protected void refreshHTTPAuth() { super.refreshHTTPAuth(); if (!httpAuth) { credProvider = null; return; } // Refresh Credentials-Provider if (httpUsername.equals(Constants.EMPTY) || httpPassword.equals(Constants.EMPTY)) { credProvider = null; } else { credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(httpUsername, httpPassword)); } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/deprecated/ApacheJSONConnector.java
Java
gpl3
8,724
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net.deprecated; import java.security.KeyStore; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.HttpParams; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.SSLUtils; import android.util.Log; /** * Create a HttpClient object based on the user preferences. */ public class HttpClientFactory { protected static final String TAG = HttpClientFactory.class.getSimpleName(); private static HttpClientFactory instance; private SchemeRegistry registry; public HttpClientFactory() { boolean trustAllSslCerts = Controller.getInstance().trustAllSsl(); boolean useCustomKeyStore = Controller.getInstance().useKeystore(); registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); SocketFactory socketFactory = null; if (useCustomKeyStore && !trustAllSslCerts) { String keystorePassword = Controller.getInstance().getKeystorePassword(); socketFactory = newSslSocketFactory(keystorePassword); if (socketFactory == null) { socketFactory = SSLSocketFactory.getSocketFactory(); Log.w(TAG, "Custom key store could not be read, using default settings."); } } else if (trustAllSslCerts) { socketFactory = new FakeSocketFactory(); } else { socketFactory = SSLSocketFactory.getSocketFactory(); } registry.register(new Scheme("https", socketFactory, 443)); } public DefaultHttpClient getHttpClient(HttpParams httpParams) { DefaultHttpClient httpInstance = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams); return httpInstance; } public static HttpClientFactory getInstance() { synchronized (HttpClientFactory.class) { if (instance == null) { instance = new HttpClientFactory(); } } return instance; } /** * Create a socket factory with the custom key store * * @param keystorePassword * the password to unlock the custom keystore * * @return socket factory with custom key store */ private static SSLSocketFactory newSslSocketFactory(String keystorePassword) { try { KeyStore keystore = SSLUtils.loadKeystore(keystorePassword); return new SSLSocketFactory(keystore); } catch (Exception e) { e.printStackTrace(); } return null; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/deprecated/HttpClientFactory.java
Java
gpl3
3,598
/* * ttrss-reader-fork for Android * * Copyright (C) 2013 I. Lubimov. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net; import org.ttrssreader.model.pojos.Article; /** * this interface is supposed to be used inside parseArticleArray of JSONConnector. The {@code omitArticle} method will * be called for each article field to determine if the article can be already omitted. * * @author igor */ public interface IArticleOmitter { /** * this method should return {@code true} if given article should not be processed * * @param field * current article field added to article on this iteration * @param a * article to test * @return {@code true} if given article should be omitted, {@code false} otherwise * @throws StopProcessingException * if parsing process should be broken */ public boolean omitArticle(Article.ArticleField field, Article a) throws StopJsonParsingException; }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/IArticleOmitter.java
Java
gpl3
1,408
/* * ttrss-reader-fork for Android * * Copyright (C) 2013 I. Lubimov. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net; /** * this exception should be thrown if parsing of JSON object should be broken * * @author igor */ public class StopJsonParsingException extends Exception { private static final long serialVersionUID = 1L; /** * constructor with detail message specification * * @param detailMessage * detailed description of exception cause */ public StopJsonParsingException(String detailMessage) { super(detailMessage); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/StopJsonParsingException.java
Java
gpl3
1,042
package org.ttrssreader.net; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; /** * <h1>Which Cipher Suites to enable for SSL Socket?</h1> * <p> * Below is the Java class I use to enforce cipher suites and protocols. Prior to SSLSocketFactoryEx, I was modifying * properties on the SSLSocket when I had access to them. The Java folks on Stack Overflow helped with it, so its nice * to be able to post it here. * </p> * * <p> * SSLSocketFactoryEx prefers stronger cipher suites (like ECDHE and DHE), and it omits weak and wounded cipher suites * (like RC4 and MD5). It does have to enable four RSA key transport ciphers for interop with Google and Microsoft when * TLS 1.2 is not available. They are TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_RSA_WITH_AES_256_CBC_SHA and two friends. * </p> * * <p> * Keep the cipher suite list as small as possible. If you advertise all available ciphers (similar to Flaschen's list), * then your list will be 80+. That takes up 160 bytes in the ClientHello, and it can cause some appliances to fail * because they have a small, fixed-size buffer for processing the ClientHello. Broken appliances include F5 and * Ironport. * </p> * * <p> * In practice, the list in the code below is paired down to 10 or 15 cipher suites once the preferred list intersects * with Java's supported cipher suites. For example, here's the list I get when preparing to connect or microsoft.com or * google.com with an unlimited JCE policy in place: * </p> * * <ul> * <li>TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384</li> * <li>TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384</li> * <li>TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256</li> * <li>TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256</li> * <li>TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384</li> * <li>TLS_DHE_DSS_WITH_AES_256_GCM_SHA384</li> * <li>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256</li> * <li>TLS_DHE_DSS_WITH_AES_128_GCM_SHA256</li> * <li>TLS_DHE_DSS_WITH_AES_256_CBC_SHA256</li> * <li>TLS_DHE_RSA_WITH_AES_128_CBC_SHA</li> * <li>TLS_DHE_DSS_WITH_AES_128_CBC_SHA</li> * <li>TLS_RSA_WITH_AES_256_CBC_SHA256</li> * <li>TLS_RSA_WITH_AES_256_CBC_SHA</li> * <li>TLS_RSA_WITH_AES_128_CBC_SHA256</li> * <li>TLS_RSA_WITH_AES_128_CBC_SHA</li> * <li>TLS_EMPTY_RENEGOTIATION_INFO_SCSV</li> * </ul> * * <p> * The list will be smaller with the default JCE policy because the policy removes AES-256 and some others. I think its * about 7 cipher suites with the restricted policy. * </p> * * <p> * The SSLSocketFactoryEx class also ensures protocols TLS 1.0 and above are used. Java clients prior to Java 8 disable * TLS 1.1 and 1.2. SSLContext.getInstance("TLS") will also sneak in SSLv3 (even in Java 8), so steps have to be taken * to remove it. * </p> * * <p> * Finally, the class below is TLS 1.3 aware, so it should work when Java provides it. The *_CHACHA20_POLY1305 cipher * suites are preferred if available because they are so much faster than some of the current suites and they have * better security properties. Google has already rolled it out on its servers. I'm not sure when Oracle will provide * them. OpenSSL will provide them with OpenSSL 1.0.2. * </p> * * <p> * You can use it like so: * </p> * * <pre> * {@code * URL url = new URL("https://www.google.com:443"); * HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); * * SSLSocketFactoryEx factory = new SSLSocketFactoryEx(); * connection.setSSLSocketFactory(factory); * connection.setRequestProperty("charset", "utf-8"); * * InputStream input = connection.getInputStream(); * InputStreamReader reader = new InputStreamReader(input, "utf-8"); * BufferedReader buffer = new BufferedReader(reader); * ... * } * </pre> * * <p> * Source: <a href="http://stackoverflow.com/a/23365536">stackoverflow.com/a/23365536</a> * </p> * * @author jww: http://stackoverflow.com/users/608639/jww * */ public class SSLSocketFactoryEx extends SSLSocketFactory { public SSLSocketFactoryEx() throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(null, null, null); } public SSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(km, tm, random); } public SSLSocketFactoryEx(SSLContext ctx) throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(ctx); } @Override public String[] getDefaultCipherSuites() { return m_ciphers; } @Override public String[] getSupportedCipherSuites() { return m_ciphers; } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(s, host, port, autoClose); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(address, port, localAddress, localPort); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(host, port, localHost, localPort); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } @Override public Socket createSocket(InetAddress host, int port) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(host, port); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } @Override public Socket createSocket(String host, int port) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(host, port); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } private void initSSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException { m_ctx = SSLContext.getInstance("TLS"); m_ctx.init(km, tm, random); m_protocols = getProtocolList(); m_ciphers = getCipherList(); } private void initSSLSocketFactoryEx(SSLContext ctx) throws NoSuchAlgorithmException, KeyManagementException { m_ctx = ctx; m_protocols = getProtocolList(); m_ciphers = getCipherList(); } protected String[] getProtocolList() { String[] preferredProtocols = { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" }; String[] availableProtocols = null; SSLSocket socket = null; try { SSLSocketFactory factory = m_ctx.getSocketFactory(); socket = (SSLSocket) factory.createSocket(); availableProtocols = socket.getSupportedProtocols(); Arrays.sort(availableProtocols); } catch (Exception e) { return new String[] { "TLSv1" }; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } List<String> aa = new ArrayList<String>(); for (int i = 0; i < preferredProtocols.length; i++) { int idx = Arrays.binarySearch(availableProtocols, preferredProtocols[i]); if (idx >= 0) aa.add(preferredProtocols[i]); } return aa.toArray(new String[0]); } protected String[] getCipherList() { String[] preferredCiphers = { // @formatter:off // *_CHACHA20_POLY1305 are 3x to 4x faster than existing cipher suites. // http://googleonlinesecurity.blogspot.com/2014/04/speeding-up-and-strengthening-https.html // Use them if available. Normative names can be found at (TLS spec depends on IPSec spec): // http://tools.ietf.org/html/draft-nir-ipsecme-chacha20-poly1305-01 // http://tools.ietf.org/html/draft-mavrogiannopoulos-chacha-tls-02 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_CHACHA20_SHA", "TLS_ECDHE_RSA_WITH_CHACHA20_SHA", "TLS_DHE_RSA_WITH_CHACHA20_POLY1305", "TLS_RSA_WITH_CHACHA20_POLY1305", "TLS_DHE_RSA_WITH_CHACHA20_SHA", "TLS_RSA_WITH_CHACHA20_SHA", // Done with bleeding edge, back to TLS v1.2 and below "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", // TLS v1.0 (with some SSLv3 interop) "TLS_DHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", // Removed SSLv3 cipher suites (see // http://www.openssl.org/docs/apps/ciphers.html#SSL_v3_0_cipher_suites_ for lists of cipher suite // names): // "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA", // "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA", // RSA key transport sucks, but they are needed as a fallback. // For example, microsoft.com fails under all versions of TLS // if they are not included. If only TLS 1.0 is available at // the client, then google.com will fail too. TLS v1.3 is // trying to deprecate them, so it will be interesteng to see // what happens. "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA" // @formatter:on }; String[] availableCiphers = null; try { SSLSocketFactory factory = m_ctx.getSocketFactory(); availableCiphers = factory.getSupportedCipherSuites(); Arrays.sort(availableCiphers); } catch (Exception e) { return new String[] { // @formatter:off "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" // @formatter:on }; } List<String> aa = new ArrayList<String>(); for (int i = 0; i < preferredCiphers.length; i++) { int idx = Arrays.binarySearch(availableCiphers, preferredCiphers[i]); if (idx >= 0) aa.add(preferredCiphers[i]); } aa.add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV"); return aa.toArray(new String[0]); } private SSLContext m_ctx; private String[] m_ciphers; private String[] m_protocols; }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/SSLSocketFactoryEx.java
Java
gpl3
13,590
/* * ttrss-reader-fork for Android * * Copyright (C) 2013 I. Lubimov. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.net; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.model.pojos.Article; /** * the instance of this class will be used for filtering out already cached articles, which was not updated while * parsing of JSON response from server * * @author igor */ public class IdUpdatedArticleOmitter implements IArticleOmitter { /** * map of article IDs to it's updated date */ private Map<Integer, Long> idUpdatedMap; /** * articles, which was skipped */ private Set<Integer> omittedArticles; /** * construct the object according to selection parameters * * @param selection * A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE * itself). Passing null will return all rows. * @param selectionArgs * You may include ?s in selection, which will be replaced by the values from selectionArgs, in order * that they appear in the selection. The values will be bound as Strings. */ public IdUpdatedArticleOmitter(String selection, String[] selectionArgs) { idUpdatedMap = DBHelper.getInstance().getArticleIdUpdatedMap(selection, selectionArgs); omittedArticles = new HashSet<Integer>(); } /** * article should be omitted if it's ID already exist in DB and updated date is not after date, which is stored in * DB * * @param field * current article field added to article on this iteration * @param a * article to test * @return {@code true} if given article should be omitted, {@code false} otherwise * @throws StopJsonParsingException * if parsing process make no sense (anymore) and should be broken */ public boolean omitArticle(Article.ArticleField field, Article a) throws StopJsonParsingException { boolean skip = false; switch (field) { case id: case updated: if (a.id > 0 && a.updated != null) { Long updated = idUpdatedMap.get(a.id); if (updated != null && a.updated.getTime() <= updated) { skip = true; omittedArticles.add(a.id); } } default: break; } return skip; } /** * map of article IDs to it's updated date * * @return the idUpdatedMap */ public Map<Integer, Long> getIdUpdatedMap() { return idUpdatedMap; } /** * map of article IDs to it's updated date * * @param idUpdatedMap * the idUpdatedMap to set */ public void setIdUpdatedMap(Map<Integer, Long> idUpdatedMap) { this.idUpdatedMap = idUpdatedMap; } /** * articles, which was skipped * * @return the omittedArticles */ public Set<Integer> getOmittedArticles() { return omittedArticles; } /** * articles, which was skipped * * @param omittedArticles * the omittedArticles to set */ public void setOmittedArticles(Set<Integer> omittedArticles) { this.omittedArticles = omittedArticles; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/net/IdUpdatedArticleOmitter.java
Java
gpl3
3,901
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import android.app.Activity; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.widget.MediaController; import android.widget.VideoView; public class MediaPlayerActivity extends Activity { protected static final String TAG = MediaPlayerActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); public static final String URL = "media_url"; private String url; private MediaPlayer mp; @Override protected void onCreate(Bundle instance) { setTheme(Controller.getInstance().getTheme()); super.onCreate(instance); mDamageReport.initialize(); setContentView(R.layout.media); Bundle extras = getIntent().getExtras(); if (extras != null) { url = extras.getString(URL); } else if (instance != null) { url = instance.getString(URL); } else { url = ""; } VideoView videoView = (VideoView) findViewById(R.id.MediaView); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoView); Uri video = Uri.parse(url); videoView.setMediaController(mediaController); videoView.setVideoURI(video); videoView.start(); } @Override protected void onResume() { if (mp != null) mp.start(); super.onResume(); } @Override protected void onPause() { if (mp != null) mp.pause(); super.onPause(); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); if (mp != null) mp.release(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/MediaPlayerActivity.java
Java
gpl3
2,577
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.interfaces; public interface IDataChangedListener { public void dataLoadingFinished(); public void dataChanged(); }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/interfaces/IDataChangedListener.java
Java
gpl3
687
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.interfaces; import org.ttrssreader.model.pojos.Article; public interface TextInputAlertCallback { public void onPublishNoteResult(Article a, String note); }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/interfaces/TextInputAlertCallback.java
Java
gpl3
710
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.interfaces; import org.ttrssreader.gui.fragments.MainListFragment; public interface IItemSelectedListener { enum TYPE { CATEGORY, FEED, FEEDHEADLINE, NONE } public void itemSelected(MainListFragment source, int selectedIndex, int selectedId); }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/interfaces/IItemSelectedListener.java
Java
gpl3
872
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.interfaces; public interface ICacheEndListener { public void onCacheEnd(); public void onCacheProgress(int taskCount, int progress); }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/interfaces/ICacheEndListener.java
Java
gpl3
706
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.interfaces; public interface IUpdateEndListener { public void onUpdateEnd(boolean goBackAfterUpdate); }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/interfaces/IUpdateEndListener.java
Java
gpl3
709
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import java.util.Date; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import org.ttrssreader.utils.Utils; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; public class AboutActivity extends Activity { protected static final String TAG = AboutActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); @Override protected void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); mDamageReport.initialize(); Window w = getWindow(); w.requestFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.about); w.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_info); TextView versionText = (TextView) this.findViewById(R.id.AboutActivity_VersionText); versionText.setText(this.getString(R.string.AboutActivity_VersionText) + " " + Utils.getAppVersionName(this)); TextView versionCodeText = (TextView) this.findViewById(R.id.AboutActivity_VersionCodeText); versionCodeText.setText(this.getString(R.string.AboutActivity_VersionCodeText) + " " + Utils.getAppVersionCode(this)); TextView licenseText = (TextView) this.findViewById(R.id.AboutActivity_LicenseText); licenseText.setText(this.getString(R.string.AboutActivity_LicenseText) + " " + this.getString(R.string.AboutActivity_LicenseTextValue)); TextView urlText = (TextView) this.findViewById(R.id.AboutActivity_UrlText); urlText.setText(this.getString(R.string.AboutActivity_UrlTextValue)); TextView lastSyncText = (TextView) this.findViewById(R.id.AboutActivity_LastSyncText); lastSyncText.setText(this.getString(R.string.AboutActivity_LastSyncText) + " " + new Date(Controller.getInstance().getLastSync())); TextView thanksText = (TextView) this.findViewById(R.id.AboutActivity_ThanksText); thanksText.setText(this.getString(R.string.AboutActivity_ThanksTextValue)); Button closeBtn = (Button) this.findViewById(R.id.AboutActivity_CloseBtn); closeBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { closeButtonPressed(); } }); Button donateBtn = (Button) this.findViewById(R.id.AboutActivity_DonateBtn); donateBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { donateButtonPressed(); } }); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } private void closeButtonPressed() { this.finish(); } private void donateButtonPressed() { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.DonateUrl)))); this.finish(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/AboutActivity.java
Java
gpl3
4,053
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.view; import android.content.Context; import android.view.View; import android.webkit.WebView; public class MyWebView extends WebView { protected static final String TAG = MyWebView.class.getSimpleName(); public MyWebView(Context context) { super(context); } public OnEdgeReachedListener mOnTopReachedListener = null; public OnEdgeReachedListener mOnBottomReachedListener = null; private int mMinTopDistance = 0; private int mMinBottomDistance = 0; /** * Set the listener which will be called when the WebView is scrolled to within some * margin of the top or bottom. * * @param bottomReachedListener * @param allowedDifference */ public void setOnTopReachedListener(OnEdgeReachedListener topReachedListener, int allowedDifference) { mOnTopReachedListener = topReachedListener; mMinTopDistance = allowedDifference; } public void setOnBottomReachedListener(OnEdgeReachedListener bottomReachedListener, int allowedDifference) { mOnBottomReachedListener = bottomReachedListener; mMinBottomDistance = allowedDifference; } /** * Implement this interface if you want to be notified when the WebView has scrolled to the top or bottom. */ public interface OnEdgeReachedListener { void onTopReached(View v, boolean reached); void onBottomReached(View v, boolean reached); } private boolean topReached = true; private boolean bottomReached = false; @Override protected void onScrollChanged(int left, int top, int oldLeft, int oldTop) { if (mOnTopReachedListener != null) handleTopReached(top); if (mOnBottomReachedListener != null) handleBottomReached(top); super.onScrollChanged(left, top, oldLeft, oldTop); } private void handleTopReached(int top) { boolean reached = false; if (top <= mMinTopDistance) reached = true; else if (top > (mMinTopDistance * 1.5)) reached = false; else return; if (!reached && !topReached) return; if (reached && topReached) return; topReached = reached; mOnTopReachedListener.onTopReached(this, reached); } private void handleBottomReached(int top) { boolean reached = false; if ((getContentHeight() - (top + getHeight())) <= mMinBottomDistance) reached = true; else if ((getContentHeight() - (top + getHeight())) > (mMinBottomDistance * 1.5)) reached = false; else return; if (!reached && !bottomReached) return; if (reached && bottomReached) return; bottomReached = reached; mOnBottomReachedListener.onBottomReached(this, reached); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/view/MyWebView.java
Java
gpl3
3,646
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.view; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Locale; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.gui.MediaPlayerActivity; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.Utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; public class ArticleWebViewClient extends WebViewClient { protected static final String TAG = ArticleWebViewClient.class.getSimpleName(); @Override public boolean shouldOverrideUrlLoading(WebView view, final String url) { final Context context = view.getContext(); boolean audioOrVideo = false; for (String s : FileUtils.AUDIO_EXTENSIONS) { if (url.toLowerCase(Locale.getDefault()).contains("." + s)) { audioOrVideo = true; break; } } for (String s : FileUtils.VIDEO_EXTENSIONS) { if (url.toLowerCase(Locale.getDefault()).contains("." + s)) { audioOrVideo = true; break; } } if (audioOrVideo) { // @formatter:off final CharSequence[] items = { (String) context.getText(R.string.WebViewClientActivity_Display), (String) context.getText(R.string.WebViewClientActivity_Download) }; // @formatter:on AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("What shall we do?"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: Log.i(TAG, "Displaying file in mediaplayer: " + url); Intent i = new Intent(context, MediaPlayerActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(MediaPlayerActivity.URL, url); context.startActivity(i); break; case 1: try { new AsyncDownloader(context).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new URL( url)); } catch (MalformedURLException e) { e.printStackTrace(); } break; default: Log.e(TAG, "Doing nothing, but why is that?? Item: " + item); break; } } }); AlertDialog alert = builder.create(); alert.show(); } else { Uri uri = Uri.parse(url); try { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean externalStorageState() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } else { return false; } } private class AsyncDownloader extends AsyncTask<URL, Void, Void> { private final static int BUFFER = (int) Utils.KB; private Context context; public AsyncDownloader(Context context) { this.context = context; } protected Void doInBackground(URL... urls) { if (urls.length < 1) { String msg = "No URL given, skipping download..."; Log.w(TAG, msg); Utils.showFinishedNotification(msg, 0, true, context); return null; } else if (!externalStorageState()) { String msg = "External Storage not available, skipping download..."; Log.w(TAG, msg); Utils.showFinishedNotification(msg, 0, true, context); return null; } Utils.showRunningNotification(context, false); URL url = urls[0]; long start = System.currentTimeMillis(); // Build name as "download_123801230712", then try to extract a proper name from URL String name = "download_" + System.currentTimeMillis(); if (!url.getFile().equals("")) { String n = url.getFile(); name = n.substring(1).replaceAll("[^A-Za-z0-9_.]", ""); if (name.contains(".") && name.length() > name.indexOf(".") + 4) { // Try to guess the position of the extension.. name = name.substring(0, name.indexOf(".") + 4); } else if (name.length() == 0) { // just to make sure.. name = "download_" + System.currentTimeMillis(); } } // Use configured output directory File folder = new File(Controller.getInstance().saveAttachmentPath()); if (!folder.exists()) { if (!folder.mkdirs()) { // Folder could not be created, fallback to internal directory on sdcard // Path: /sdcard/Android/data/org.ttrssreader/files/ folder = new File(Constants.SAVE_ATTACHMENT_DEFAULT); folder.mkdirs(); } } if (!folder.exists()) folder.mkdirs(); BufferedInputStream in = null; FileOutputStream fos = null; BufferedOutputStream bout = null; int count = -1; File file = null; try { HttpURLConnection c = (HttpURLConnection) url.openConnection(); file = new File(folder, name); if (file.exists()) { count = (int) file.length(); c.setRequestProperty("Range", "bytes=" + file.length() + "-"); // try to resume downloads } c.setRequestMethod("GET"); c.setDoInput(true); c.setDoOutput(true); in = new BufferedInputStream(c.getInputStream()); fos = (count == 0) ? new FileOutputStream(file) : new FileOutputStream(file, true); bout = new BufferedOutputStream(fos, BUFFER); byte[] data = new byte[BUFFER]; int x = 0; while ((x = in.read(data, 0, BUFFER)) >= 0) { bout.write(data, 0, x); count += x; } int time = (int) ((System.currentTimeMillis() - start) / Utils.SECOND); // Show Intent which opens the file Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); if (file != null) intent.setDataAndType(Uri.fromFile(file), FileUtils.getMimeType(file.getName())); Log.i(TAG, "Finished. Path: " + file.getAbsolutePath() + " Time: " + time + "s Bytes: " + count); Utils.showFinishedNotification(file.getAbsolutePath(), time, false, context, intent); } catch (IOException e) { String msg = "Error while downloading: " + e; Log.e(TAG, msg); e.printStackTrace(); Utils.showFinishedNotification(msg, 0, true, context); } finally { // Remove "running"-notification Utils.showRunningNotification(context, true); if (bout != null) { try { bout.close(); } catch (IOException e) { } } } return null; } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/view/ArticleWebViewClient.java
Java
gpl3
9,703
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.view; import org.ttrssreader.controllers.Controller; import android.app.ActionBar; import android.view.GestureDetector; import android.view.MotionEvent; public class MyGestureDetector extends GestureDetector.SimpleOnGestureListener { protected static final String TAG = MyGestureDetector.class.getSimpleName(); private ActionBar actionBar; private boolean hideActionbar; private long lastShow = -1; public MyGestureDetector(ActionBar actionBar, boolean hideActionbar) { this.actionBar = actionBar; this.hideActionbar = hideActionbar; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (!hideActionbar) return false; if (Controller.isTablet) return false; if (System.currentTimeMillis() - lastShow < 700) return false; if (Math.abs(distanceX) > Math.abs(distanceY)) return false; if (distanceY < -10) { actionBar.show(); lastShow = System.currentTimeMillis(); } else if (distanceY > 10) { actionBar.hide(); lastShow = System.currentTimeMillis(); } return false; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/view/MyGestureDetector.java
Java
gpl3
1,913
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.model.pojos.Article; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.EditText; public class TextInputAlert { protected static final String TAG = TextInputAlert.class.getSimpleName(); private Article article; private TextInputAlertCallback callback; public TextInputAlert(TextInputAlertCallback callback, Article article) { this.callback = callback; this.article = article; } public void show(Context context) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle(context.getString(R.string.Commons_MarkPublishNote)); final EditText input = new EditText(context); input.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); input.setMinLines(3); input.setMaxLines(10); alert.setView(input); alert.setPositiveButton(context.getString(R.string.Utils_OkayAction), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); callback.onPublishNoteResult(article, value); } }); alert.setNegativeButton(context.getString(R.string.Utils_CancelAction), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); alert.show(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/TextInputAlert.java
Java
gpl3
2,360
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * <http://www.apache.org/licenses/LICENSE-2.0> * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.imageCache.PluginReceiver; import org.ttrssreader.imageCache.bundle.BundleScrubber; import org.ttrssreader.imageCache.bundle.PluginBundleManager; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.CheckBox; /** * This is the "Edit" activity for a Locale Plug-in. * <p> * This Activity can be started in one of two states: * <ul> * <li>New plug-in instance: The Activity's Intent will not contain * {@link com.twofortyfouram.locale.Intent#EXTRA_BUNDLE}.</li> * <li>Old plug-in instance: The Activity's Intent will contain {@link com.twofortyfouram.locale.Intent#EXTRA_BUNDLE} * from a previously saved plug-in instance that the user is editing.</li> * </ul> * * @see com.twofortyfouram.locale.Intent#ACTION_EDIT_SETTING * @see com.twofortyfouram.locale.Intent#EXTRA_BUNDLE */ public final class EditPluginActivity extends AbstractPluginActivity { protected static final String TAG = EditPluginActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDamageReport.initialize(); BundleScrubber.scrub(getIntent()); final Bundle localeBundle = getIntent().getBundleExtra(PluginReceiver.EXTRA_BUNDLE); BundleScrubber.scrub(localeBundle); setContentView(R.layout.localeplugin); if (null == savedInstanceState) { if (PluginBundleManager.isBundleValid(localeBundle)) { final boolean images = localeBundle.getBoolean(PluginBundleManager.BUNDLE_EXTRA_IMAGES); final boolean notification = localeBundle.getBoolean(PluginBundleManager.BUNDLE_EXTRA_NOTIFICATION); ((CheckBox) findViewById(R.id.cb_images)).setChecked(images); ((CheckBox) findViewById(R.id.cb_notification)).setChecked(notification); } } } @Override public void finish() { if (!isCanceled()) { final boolean images = ((CheckBox) findViewById(R.id.cb_images)).isChecked(); final boolean notification = ((CheckBox) findViewById(R.id.cb_notification)).isChecked(); final Intent resultIntent = new Intent(); /* * This extra is the data to ourselves: either for the Activity or the BroadcastReceiver. Note * that anything placed in this Bundle must be available to Locale's class loader. So storing * String, int, and other standard objects will work just fine. Parcelable objects are not * acceptable, unless they also implement Serializable. Serializable objects must be standard * Android platform objects (A Serializable class private to this plug-in's APK cannot be * stored in the Bundle, as Locale's classloader will not recognize it). */ final Bundle result = PluginBundleManager.generateBundle(getApplicationContext(), images, notification); resultIntent.putExtra(PluginReceiver.EXTRA_BUNDLE, result); /* * The blurb is concise status text to be displayed in the host's UI. */ final String blurb = generateBlurb(getApplicationContext(), images, notification); resultIntent.putExtra(com.twofortyfouram.locale.Intent.EXTRA_STRING_BLURB, blurb); setResult(RESULT_OK, resultIntent); } super.finish(); } /* package */static String generateBlurb(final Context context, final boolean images, final boolean notification) { String imageText = (images ? "Caching images" : "Not caching images"); String notificationText = (notification ? "Showing notification" : "Not showing notification"); return imageText + ", " + notificationText; } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/EditPluginActivity.java
Java
gpl3
5,040
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import java.lang.reflect.Field; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.ProgressBarManager; import org.ttrssreader.controllers.UpdateController; import org.ttrssreader.gui.dialogs.ErrorDialog; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.gui.interfaces.IDataChangedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.gui.interfaces.IUpdateEndListener; import org.ttrssreader.imageCache.ForegroundService; import org.ttrssreader.model.updaters.StateSynchronisationUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import org.ttrssreader.utils.Utils; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Rect; import android.os.Bundle; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; /** * This class provides common functionality for Activities. */ public abstract class MenuActivity extends Activity implements IUpdateEndListener, ICacheEndListener, IItemSelectedListener, IDataChangedListener { protected static final String TAG = MenuActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); protected final Context context = this; protected Updater updater; protected Activity activity; protected boolean isVertical; protected static int minSize; protected static int maxSize; protected int dividerSize; protected int displaySize; private View frameMain = null; private View divider = null; private View frameSub = null; private TextView header_title; private TextView header_unread; @Override protected void onCreate(Bundle instance) { setTheme(Controller.getInstance().getTheme()); super.onCreate(instance); mDamageReport.initialize(); activity = this; requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); Controller.getInstance().setHeadless(false); initActionbar(); getOverflowMenu(); } protected void initTabletLayout() { frameMain = findViewById(R.id.frame_main); divider = findViewById(R.id.list_divider); frameSub = findViewById(R.id.frame_sub); if (frameMain == null || frameSub == null || divider == null) return; // Do nothing, the views do not exist... // Initialize values for layout changes: Controller .refreshDisplayMetrics(((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()); isVertical = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT); displaySize = Controller.displayWidth; if (isVertical) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true); int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId); displaySize = Controller.displayHeight - actionBarHeight; } minSize = (int) (displaySize * 0.1); maxSize = displaySize - (int) (displaySize * 0.1); // use tablet layout? if (Controller.getInstance().allowTabletLayout()) Controller.isTablet = divider != null; else Controller.isTablet = false; // Set frame sizes and hide divider if necessary if (Controller.isTablet) { // Resize frames and do it only if stored size is within our bounds: int mainFrameSize = Controller.getInstance().getMainFrameSize(this, isVertical, minSize, maxSize); int subFrameSize = displaySize - mainFrameSize; LayoutParams lpMain = (RelativeLayout.LayoutParams) frameMain.getLayoutParams(); LayoutParams lpSub = (RelativeLayout.LayoutParams) frameSub.getLayoutParams(); if (isVertical) { // calculate height of divider int padding = divider.getPaddingTop() + divider.getPaddingBottom(); dividerSize = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, padding, context .getResources().getDisplayMetrics())); // Create LayoutParams for all three views lpMain.height = mainFrameSize; lpSub.height = subFrameSize - dividerSize; lpSub.addRule(RelativeLayout.BELOW, divider.getId()); } else { // calculate width of divider int padding = divider.getPaddingLeft() + divider.getPaddingRight(); dividerSize = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, padding, context .getResources().getDisplayMetrics())); // Create LayoutParams for all three views lpMain.width = mainFrameSize; lpSub.width = subFrameSize - dividerSize; lpSub.addRule(RelativeLayout.RIGHT_OF, divider.getId()); } // Set all params and visibility frameMain.setLayoutParams(lpMain); frameSub.setLayoutParams(lpSub); divider.setVisibility(View.VISIBLE); getWindow().getDecorView().getRootView().invalidate(); } else { frameMain.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); frameSub.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); if (divider != null) divider.setVisibility(View.GONE); } } protected void handleResize() { int mainFrameSize = calculateSize((int) (frameMain.getHeight() + (isVertical ? mDeltaY : mDeltaX))); int subFrameSize = displaySize - dividerSize - mainFrameSize; LayoutParams lpMain = (RelativeLayout.LayoutParams) frameMain.getLayoutParams(); LayoutParams lpSub = (RelativeLayout.LayoutParams) frameSub.getLayoutParams(); if (isVertical) { lpMain.height = mainFrameSize; lpSub.height = subFrameSize; } else { lpMain.width = mainFrameSize; lpSub.width = subFrameSize; } frameMain.setLayoutParams(lpMain); frameSub.setLayoutParams(lpSub); getWindow().getDecorView().getRootView().invalidate(); } @SuppressLint("InflateParams") private void initActionbar() { // Go to the CategoryActivity and clean the return-stack // getSupportActionBar().setHomeButtonEnabled(true); ActionBar.LayoutParams params = new ActionBar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View actionbarView = inflator.inflate(R.layout.actionbar, null); ActionBar ab = getActionBar(); ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ab.setDisplayHomeAsUpEnabled(true); ab.setDisplayShowCustomEnabled(true); ab.setDisplayShowTitleEnabled(false); ab.setCustomView(actionbarView, params); header_unread = (TextView) actionbarView.findViewById(R.id.head_unread); header_title = (TextView) actionbarView.findViewById(R.id.head_title); header_title.setText(getString(R.string.ApplicationName)); } @Override public void setTitle(CharSequence title) { header_title.setText(title); super.setTitle(title); } public void setUnread(int unread) { if (unread > 0) { header_unread.setVisibility(View.VISIBLE); } else { header_unread.setVisibility(View.GONE); } header_unread.setText("( " + unread + " )"); } /** * Force-display the three dots for overflow, would be disabled on devices with a menu-key. * * @see http://stackoverflow.com/a/13098824 */ private void getOverflowMenu() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception e) { } } @Override protected void onResume() { super.onResume(); if (Controller.getInstance().isScheduledRestart()) { Controller.getInstance().setScheduledRestart(false); Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else { UpdateController.getInstance().registerActivity(this); DBHelper.getInstance().checkAndInitializeDB(this); } refreshAndUpdate(); } @Override protected void onStop() { super.onStop(); UpdateController.getInstance().unregisterActivity(this); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); if (updater != null) { updater.cancel(true); updater = null; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == ErrorActivity.ACTIVITY_SHOW_ERROR) { refreshAndUpdate(); } else if (resultCode == PreferencesActivity.ACTIVITY_SHOW_PREFERENCES) { refreshAndUpdate(); } else if (resultCode == ErrorActivity.ACTIVITY_EXIT) { finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.generic, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem offline = menu.findItem(R.id.Menu_WorkOffline); MenuItem refresh = menu.findItem(R.id.Menu_Refresh); if (offline != null) { if (Controller.getInstance().workOffline()) { offline.setTitle(getString(R.string.UsageOnlineTitle)); offline.setIcon(R.drawable.ic_menu_play_clip); if (refresh != null) menu.findItem(R.id.Menu_Refresh).setVisible(false); } else { offline.setTitle(getString(R.string.UsageOfflineTitle)); offline.setIcon(R.drawable.ic_menu_stop); if (refresh != null) menu.findItem(R.id.Menu_Refresh).setVisible(true); } } MenuItem displayUnread = menu.findItem(R.id.Menu_DisplayOnlyUnread); if (displayUnread != null) { if (Controller.getInstance().onlyUnread()) { displayUnread.setTitle(getString(R.string.Commons_DisplayAll)); } else { displayUnread.setTitle(getString(R.string.Commons_DisplayOnlyUnread)); } } MenuItem displayOnlyCachedImages = menu.findItem(R.id.Menu_DisplayOnlyCachedImages); if (displayOnlyCachedImages != null) { if (Controller.getInstance().onlyDisplayCachedImages()) { displayOnlyCachedImages.setTitle(getString(R.string.Commons_DisplayAll)); } else { displayOnlyCachedImages.setTitle(getString(R.string.Commons_DisplayOnlyCachedImages)); } } if (!(this instanceof FeedHeadlineActivity)) { menu.removeItem(R.id.Menu_FeedUnsubscribe); } return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case android.R.id.home: // Go to the CategoryActivity and clean the return-stack Intent intent = new Intent(this, CategoryActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; case R.id.Menu_DisplayOnlyUnread: Controller.getInstance().setDisplayOnlyUnread(!Controller.getInstance().onlyUnread()); doRefresh(); return true; case R.id.Menu_DisplayOnlyCachedImages: Controller.getInstance().setDisplayCachedImages(!Controller.getInstance().onlyDisplayCachedImages()); doRefresh(); return true; case R.id.Menu_InvertSort: if (this instanceof FeedHeadlineActivity) { Controller.getInstance() .setInvertSortArticleList(!Controller.getInstance().invertSortArticlelist()); } else { Controller.getInstance().setInvertSortFeedsCats(!Controller.getInstance().invertSortFeedscats()); } doRefresh(); return true; case R.id.Menu_WorkOffline: Controller.getInstance().setWorkOffline(!Controller.getInstance().workOffline()); if (!Controller.getInstance().workOffline()) { // Synchronize status of articles with server new Updater(this, new StateSynchronisationUpdater()).exec(); } doRefresh(); return true; case R.id.Menu_ShowPreferences: startActivityForResult(new Intent(this, PreferencesActivity.class), PreferencesActivity.ACTIVITY_SHOW_PREFERENCES); return true; case R.id.Menu_About: startActivity(new Intent(this, AboutActivity.class)); return true; case R.id.Category_Menu_ImageCache: doCache(false); return true; case R.id.Menu_FeedSubscribe: startActivity(new Intent(this, SubscribeActivity.class)); return true; default: return false; } } @Override public void onUpdateEnd(boolean goBackAfterUpdate) { updater = null; doRefresh(); if (goBackAfterUpdate && !isFinishing()) onBackPressed(); } /* ############# BEGIN: Cache */ protected void doCache(boolean onlyArticles) { // Register for progress-updates ForegroundService.registerCallback(this); if (isCacherRunning()) { if (!onlyArticles) // Tell cacher to do images too ForegroundService.loadImagesToo(); else // Running and already caching images, no need to do anything return; } // Start new cacher Intent intent; if (onlyArticles) { intent = new Intent(ForegroundService.ACTION_LOAD_ARTICLES); } else { intent = new Intent(ForegroundService.ACTION_LOAD_IMAGES); } intent.setClass(this.getApplicationContext(), ForegroundService.class); this.startService(intent); ProgressBarManager.getInstance().addProgress(this); setProgressBarVisibility(true); } @Override public void onCacheEnd() { setProgressBarVisibility(false); ProgressBarManager.getInstance().removeProgress(this); } @Override public void onCacheProgress(int taskCount, int progress) { if (taskCount == 0) setProgress(0); else setProgress((10000 / taskCount) * progress); } protected boolean isCacherRunning() { return ForegroundService.isInstanceCreated(); } /* ############# END: Cache */ protected void openConnectionErrorDialog(String errorMessage) { if (updater != null) { updater.cancel(true); updater = null; } setProgressBarVisibility(false); ProgressBarManager.getInstance().resetProgress(this); Intent i = new Intent(this, ErrorActivity.class); i.putExtra(ErrorActivity.ERROR_MESSAGE, errorMessage); startActivityForResult(i, ErrorActivity.ACTIVITY_SHOW_ERROR); } protected void showErrorDialog(String message) { ErrorDialog.getInstance(this, message).show(getFragmentManager(), "error"); } protected void refreshAndUpdate() { initTabletLayout(); if (!Utils.checkIsConfigInvalid()) { doUpdate(false); doRefresh(); } } @Override public final void dataChanged() { doRefresh(); } @Override public void dataLoadingFinished() { // Empty! } protected void doRefresh() { invalidateOptionsMenu(); ProgressBarManager.getInstance().setIndeterminateVisibility(this); if (Controller.getInstance().getConnector().hasLastError()) openConnectionErrorDialog(Controller.getInstance().getConnector().pullLastError()); } protected abstract void doUpdate(boolean forceUpdate); /** * Can be used in child activities to update their data and get a UI refresh afterwards. */ abstract class ActivityUpdater extends AsyncTask<Void, Integer, Void> { protected int taskCount = 0; protected boolean forceUpdate; public ActivityUpdater(boolean forceUpdate) { this.forceUpdate = forceUpdate; ProgressBarManager.getInstance().addProgress(activity); setProgressBarVisibility(true); } @Override protected void onProgressUpdate(Integer... values) { if (values[0] == taskCount) { setProgressBarVisibility(false); if (!isCacherRunning()) ProgressBarManager.getInstance().removeProgress(activity); return; } setProgress((10000 / (taskCount + 1)) * values[0]); } } protected static void removeOldFragment(FragmentManager fm, Fragment fragment) { FragmentTransaction ft = fm.beginTransaction(); ft.remove(fragment); ft.commit(); fm.executePendingTransactions(); } // The "active pointer" is the one currently moving our object. private static final int INVALID_POINTER_ID = -1; private int mActivePointerId = INVALID_POINTER_ID; private float mLastTouchX = 0; private float mLastTouchY = 0; private int mDeltaX = 0; private int mDeltaY = 0; private boolean resizing = false; @Override public boolean onTouchEvent(MotionEvent ev) { if (!Controller.isTablet) return false; // Only handle events when the list-divider is selected or we are already resizing: View view = findViewAtPosition(getWindow().getDecorView().getRootView(), (int) ev.getRawX(), (int) ev.getRawY()); if (view == null && !resizing) return false; switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: { divider.setSelected(true); resizing = true; final int pointerIndex = ev.getActionIndex(); // Remember where we started (for dragging) mLastTouchX = ev.getX(pointerIndex); mLastTouchY = ev.getY(pointerIndex); mDeltaX = 0; mDeltaY = 0; // Save the ID of this pointer (for dragging) mActivePointerId = ev.getPointerId(0); break; } case MotionEvent.ACTION_MOVE: { // Find the index of the active pointer and fetch its position final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex < 0) break; final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); // Calculate the distance moved mDeltaX = (int) (x - mLastTouchX); mDeltaY = (int) (y - mLastTouchY); // Store location for next difference mLastTouchX = x; mLastTouchY = y; handleResize(); break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: default: mActivePointerId = INVALID_POINTER_ID; handleResize(); storeSize(); divider.setSelected(false); resizing = false; break; } return true; } private int calculateSize(final int size) { int ret = size; if (ret < minSize) ret = minSize; if (ret > maxSize) ret = maxSize; return ret; } private void storeSize() { int size = isVertical ? frameMain.getHeight() : frameMain.getWidth(); Controller.getInstance().setViewSize(this, isVertical, size); } private static View findViewAtPosition(View parent, int x, int y) { if (parent instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) parent; for (int i = 0; i < viewGroup.getChildCount(); i++) { View child = viewGroup.getChildAt(i); View viewAtPosition = findViewAtPosition(child, x, y); if (viewAtPosition != null) { return viewAtPosition; } } return null; } else { Rect rect = new Rect(); parent.getGlobalVisibleRect(rect); if (rect.contains(x, y)) { return parent; } else { return null; } } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/MenuActivity.java
Java
gpl3
24,192
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.fragments.MainListFragment; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import android.app.ProgressDialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; public class ShareActivity extends MenuActivity { protected static final String TAG = ShareActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); private static final String PARAM_TITLE = "title"; private static final String PARAM_URL = "url"; private static final String PARAM_CONTENT = "content"; private Button shareButton; private EditText title; private EditText url; private EditText content; private ProgressDialog progress; @Override public void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); mDamageReport.initialize(); setContentView(R.layout.sharetopublished); setTitle(R.string.IntentPublish); String titleValue = getIntent().getStringExtra(Intent.EXTRA_SUBJECT); String urlValue = getIntent().getStringExtra(Intent.EXTRA_TEXT); String contentValue = ""; if (savedInstanceState != null) { titleValue = savedInstanceState.getString(PARAM_TITLE); urlValue = savedInstanceState.getString(PARAM_URL); contentValue = savedInstanceState.getString(PARAM_CONTENT); } title = (EditText) findViewById(R.id.share_title); url = (EditText) findViewById(R.id.share_url); content = (EditText) findViewById(R.id.share_content); title.setText(titleValue); url.setText(urlValue); content.setText(contentValue); shareButton = (Button) findViewById(R.id.share_ok_button); shareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progress = ProgressDialog.show(context, null, "Sending..."); new MyPublisherTask().execute(); } }); } @Override protected void onResume() { super.onResume(); doRefresh(); } @Override public void onSaveInstanceState(Bundle out) { super.onSaveInstanceState(out); EditText url = (EditText) findViewById(R.id.share_url); EditText title = (EditText) findViewById(R.id.share_title); EditText content = (EditText) findViewById(R.id.share_content); out.putString(PARAM_TITLE, title.getText().toString()); out.putString(PARAM_URL, url.getText().toString()); out.putString(PARAM_CONTENT, content.getText().toString()); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } public class MyPublisherTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { String titleValue = title.getText().toString(); String urlValue = url.getText().toString(); String contentValue = content.getText().toString(); try { boolean ret = Data.getInstance().shareToPublished(titleValue, urlValue, contentValue); progress.dismiss(); if (ret) finishCompat(); else if (Controller.getInstance().getConnector().hasLastError()) showErrorDialog(Controller.getInstance().getConnector().pullLastError()); else if (Controller.getInstance().workOffline()) showErrorDialog("Working offline, synchronisation of published articles is not implemented yet."); else showErrorDialog("An unknown error occurred."); } catch (RuntimeException r) { showErrorDialog(r.getMessage()); } return null; } private void finishCompat() { if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) finishAffinity(); else finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (super.onCreateOptionsMenu(menu)) { menu.removeItem(R.id.Menu_Refresh); menu.removeItem(R.id.Menu_MarkAllRead); menu.removeItem(R.id.Menu_MarkFeedsRead); menu.removeItem(R.id.Menu_MarkFeedRead); menu.removeItem(R.id.Menu_FeedSubscribe); menu.removeItem(R.id.Menu_FeedUnsubscribe); menu.removeItem(R.id.Menu_DisplayOnlyUnread); menu.removeItem(R.id.Menu_InvertSort); } return true; } // @formatter:off // Not needed here: @Override public void itemSelected(MainListFragment source, int selectedIndex, int selectedId) { } @Override protected void doUpdate(boolean forceUpdate) { } //@formatter:on }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/ShareActivity.java
Java
gpl3
6,113
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.fragments; import java.util.ArrayList; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.gui.FeedHeadlineActivity; import org.ttrssreader.gui.TextInputAlert; import org.ttrssreader.gui.dialogs.YesNoUpdaterDialog; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.gui.view.MyGestureDetector; import org.ttrssreader.model.FeedAdapter; import org.ttrssreader.model.FeedHeadlineAdapter; import org.ttrssreader.model.ListContentProvider; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.updaters.PublishedStateUpdater; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.StarredStateUpdater; import org.ttrssreader.model.updaters.UnsubscribeUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.Utils; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Vibrator; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; public class FeedHeadlineListFragment extends MainListFragment implements TextInputAlertCallback { protected static final String TAG = FeedHeadlineListFragment.class.getSimpleName(); protected static final TYPE THIS_TYPE = TYPE.FEEDHEADLINE; public static final String FRAGMENT = "FEEDHEADLINE_FRAGMENT"; public static final String FEED_CAT_ID = "FEED_CAT_ID"; public static final String FEED_ID = "ARTICLE_FEED_ID"; public static final String ARTICLE_ID = "ARTICLE_ID"; public static final String FEED_TITLE = "FEED_TITLE"; public static final String FEED_SELECT_ARTICLES = "FEED_SELECT_ARTICLES"; public static final String FEED_INDEX = "INDEX"; private static final int MARK_GROUP = 200; private static final int MARK_READ = MARK_GROUP + 1; private static final int MARK_STAR = MARK_GROUP + 2; private static final int MARK_PUBLISH = MARK_GROUP + 3; private static final int MARK_PUBLISH_NOTE = MARK_GROUP + 4; private static final int MARK_ABOVE_READ = MARK_GROUP + 5; private static final int SHARE = MARK_GROUP + 6; private int categoryId = Integer.MIN_VALUE; private int feedId = Integer.MIN_VALUE; private int articleId = Integer.MIN_VALUE; private boolean selectArticlesForCategory = false; private FeedAdapter parentAdapter; private List<Integer> parentIds = null; private int[] parentIdsBeforeAndAfter = new int[2]; private Uri headlineUri; private Uri feedUri; public static FeedHeadlineListFragment newInstance(int id, int categoryId, boolean selectArticles, int articleId) { FeedHeadlineListFragment detail = new FeedHeadlineListFragment(); detail.categoryId = categoryId; detail.feedId = id; detail.selectArticlesForCategory = selectArticles; detail.articleId = articleId; detail.setRetainInstance(true); return detail; } @Override public void onCreate(Bundle instance) { if (instance != null) { categoryId = instance.getInt(FEED_CAT_ID); feedId = instance.getInt(FEED_ID); selectArticlesForCategory = instance.getBoolean(FEED_SELECT_ARTICLES); articleId = instance.getInt(ARTICLE_ID); } if (feedId > 0) Controller.getInstance().lastOpenedFeeds.add(feedId); Controller.getInstance().lastOpenedArticles.clear(); setHasOptionsMenu(true); super.onCreate(instance); } @Override public void onActivityCreated(Bundle instance) { adapter = new FeedHeadlineAdapter(getActivity(), feedId, selectArticlesForCategory); getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); super.onActivityCreated(instance); // Detect touch gestures like swipe and scroll down: ActionBar actionBar = getActivity().getActionBar(); gestureDetector = new GestureDetector(getActivity(), new HeadlineGestureDetector(actionBar, Controller .getInstance().hideActionbar())); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event) || v.performClick(); } }; getView().setOnTouchListener(gestureListener); parentAdapter = new FeedAdapter(getActivity()); getLoaderManager().restartLoader(TYPE_FEED_ID, null, this); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(FEED_CAT_ID, categoryId); outState.putInt(FEED_ID, feedId); outState.putBoolean(FEED_SELECT_ARTICLES, selectArticlesForCategory); outState.putInt(ARTICLE_ID, articleId); super.onSaveInstanceState(outState); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // Get selected Article AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Article a = (Article) adapter.getItem(info.position); menu.add(MARK_GROUP, MARK_ABOVE_READ, Menu.NONE, R.string.Commons_MarkAboveRead); if (a.isUnread) { menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkRead); } else { menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkUnread); } if (a.isStarred) { menu.add(MARK_GROUP, MARK_STAR, Menu.NONE, R.string.Commons_MarkUnstar); } else { menu.add(MARK_GROUP, MARK_STAR, Menu.NONE, R.string.Commons_MarkStar); } if (a.isPublished) { menu.add(MARK_GROUP, MARK_PUBLISH, Menu.NONE, R.string.Commons_MarkUnpublish); } else { menu.add(MARK_GROUP, MARK_PUBLISH, Menu.NONE, R.string.Commons_MarkPublish); menu.add(MARK_GROUP, MARK_PUBLISH_NOTE, Menu.NONE, R.string.Commons_MarkPublishNote); } menu.add(MARK_GROUP, SHARE, Menu.NONE, R.string.ArticleActivity_ShareLink); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); if (cmi == null) return false; Article a = (Article) adapter.getItem(cmi.position); if (a == null) return false; switch (item.getItemId()) { case MARK_READ: new Updater(getActivity(), new ReadStateUpdater(a, feedId, a.isUnread ? 0 : 1)).exec(); break; case MARK_STAR: new Updater(getActivity(), new StarredStateUpdater(a, a.isStarred ? 0 : 1)).exec(); break; case MARK_PUBLISH: new Updater(getActivity(), new PublishedStateUpdater(a, a.isPublished ? 0 : 1)).exec(); break; case MARK_PUBLISH_NOTE: new TextInputAlert(this, a).show(getActivity()); break; case MARK_ABOVE_READ: new Updater(getActivity(), new ReadStateUpdater(getUnreadAbove(cmi.position), feedId, 0)).exec(); break; case SHARE: Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, a.url); i.putExtra(Intent.EXTRA_SUBJECT, a.title); startActivity(Intent.createChooser(i, (String) getText(R.string.ArticleActivity_ShareTitle))); break; default: return false; } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case R.id.Menu_MarkFeedRead: { boolean backAfterUpdate = Controller.getInstance().goBackAfterMarkAllRead(); if (selectArticlesForCategory) { new Updater(getActivity(), new ReadStateUpdater(categoryId), backAfterUpdate).exec(); } else { new Updater(getActivity(), new ReadStateUpdater(feedId, 42), backAfterUpdate).exec(); } return true; } case R.id.Menu_FeedUnsubscribe: { YesNoUpdaterDialog dialog = YesNoUpdaterDialog.getInstance(new UnsubscribeUpdater(feedId), R.string.Dialog_unsubscribeTitle, R.string.Dialog_unsubscribeText); dialog.show(getFragmentManager(), YesNoUpdaterDialog.DIALOG); return true; } default: return false; } } /** * Creates a list of articles which are above the given index in the currently displayed list of items. * * @param index * the selected index, will be excluded in returned list * @return a list of items above the selected item */ private List<Article> getUnreadAbove(int index) { List<Article> ret = new ArrayList<Article>(); for (int i = 0; i < index; i++) { Article a = (Article) adapter.getItem(i); if (a != null && a.isUnread) ret.add(a); } return ret; } public void onPublishNoteResult(Article a, String note) { new Updater(getActivity(), new PublishedStateUpdater(a, a.isPublished ? 0 : 1, note)).exec(); } @Override public TYPE getType() { return THIS_TYPE; } public int getCategoryId() { return categoryId; } public int getFeedId() { return feedId; } public int getArticleId() { return articleId; } public boolean getSelectArticlesForCategory() { return selectArticlesForCategory; } class HeadlineGestureDetector extends MyGestureDetector { public HeadlineGestureDetector(ActionBar actionBar, boolean hideActionbar) { super(actionBar, hideActionbar); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // Refresh metrics-data in Controller Controller.refreshDisplayMetrics(((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay()); try { if (Math.abs(e1.getY() - e2.getY()) > Controller.relSwipeMaxOffPath) return false; if (e1.getX() - e2.getX() > Controller.relSwipeMinDistance && Math.abs(velocityX) > Controller.relSwipteThresholdVelocity) { // right to left swipe FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextFeed(1); return true; } else if (e2.getX() - e1.getX() > Controller.relSwipeMinDistance && Math.abs(velocityX) > Controller.relSwipteThresholdVelocity) { // left to right swipe FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextFeed(-1); return true; } } catch (Exception e) { } return false; } }; private void fillParentInformation() { if (parentIds == null) { parentIds = new ArrayList<Integer>(parentAdapter.getCount() + 2); parentIds.add(Integer.MIN_VALUE); parentIds.addAll(parentAdapter.getIds()); parentIds.add(Integer.MIN_VALUE); parentAdapter.notifyDataSetInvalidated(); // Not needed anymore } // Added dummy-elements at top and bottom of list for easier access, index == 0 cannot happen. int index = -1; int i = 0; for (Integer id : parentIds) { if (id.intValue() == feedId) { index = i; break; } i++; } if (index > 0) { parentIdsBeforeAndAfter[0] = parentIds.get(index - 1); // Previous parentIdsBeforeAndAfter[1] = parentIds.get(index + 1); // Next } else { parentIdsBeforeAndAfter[0] = Integer.MIN_VALUE; parentIdsBeforeAndAfter[1] = Integer.MIN_VALUE; } } public int openNextFeed(int direction) { if (feedId < 0) return feedId; int id = direction < 0 ? parentIdsBeforeAndAfter[0] : parentIdsBeforeAndAfter[1]; if (id == Integer.MIN_VALUE) { ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); return feedId; } feedId = id; adapter = new FeedHeadlineAdapter(getActivity(), feedId, selectArticlesForCategory); setListAdapter(adapter); getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); fillParentInformation(); // Find next id in this direction and see if there is another next article or not id = direction < 0 ? parentIdsBeforeAndAfter[0] : parentIdsBeforeAndAfter[1]; if (id == Integer.MIN_VALUE) { ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); } if (feedId > 0) Controller.getInstance().lastOpenedFeeds.add(feedId); Controller.getInstance().lastOpenedArticles.clear(); getActivity().invalidateOptionsMenu(); // Force redraw of menu items in actionbar return feedId; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case TYPE_HEADLINE_ID: { Builder builder = ListContentProvider.CONTENT_URI_HEAD.buildUpon(); builder.appendQueryParameter(ListContentProvider.PARAM_CAT_ID, categoryId + ""); builder.appendQueryParameter(ListContentProvider.PARAM_FEED_ID, feedId + ""); builder.appendQueryParameter(ListContentProvider.PARAM_SELECT_FOR_CAT, (selectArticlesForCategory ? "1" : "0")); headlineUri = builder.build(); return new CursorLoader(getActivity(), headlineUri, null, null, null, null); } case TYPE_FEED_ID: { Builder builder = ListContentProvider.CONTENT_URI_FEED.buildUpon(); builder.appendQueryParameter(ListContentProvider.PARAM_CAT_ID, categoryId + ""); feedUri = builder.build(); return new CursorLoader(getActivity(), feedUri, null, null, null, null); } } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch (loader.getId()) { case TYPE_HEADLINE_ID: adapter.changeCursor(data); break; case TYPE_FEED_ID: parentAdapter.changeCursor(data); fillParentInformation(); break; } super.onLoadFinished(loader, data); } @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case TYPE_HEADLINE_ID: adapter.changeCursor(null); break; case TYPE_FEED_ID: parentAdapter.changeCursor(null); break; } } @Override protected void fetchOtherData() { if (selectArticlesForCategory) { Category category = DBHelper.getInstance().getCategory(categoryId); if (category != null) title = category.title; } else if (feedId >= -4 && feedId < 0) { // Virtual Category Category category = DBHelper.getInstance().getCategory(feedId); if (category != null) title = category.title; } else { Feed feed = DBHelper.getInstance().getFeed(feedId); if (feed != null) title = feed.title; } unreadCount = DBHelper.getInstance().getUnreadCount(selectArticlesForCategory ? categoryId : feedId, selectArticlesForCategory); } @Override public void doRefresh() { // getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); Activity activity = getActivity(); if (activity != null && headlineUri != null) activity.getContentResolver().notifyChange(headlineUri, null); super.doRefresh(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/fragments/FeedHeadlineListFragment.java
Java
gpl3
18,421
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.fragments; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.gui.dialogs.YesNoUpdaterDialog; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.model.FeedAdapter; import org.ttrssreader.model.ListContentProvider; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.UnsubscribeUpdater; import org.ttrssreader.model.updaters.Updater; import android.app.Activity; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; public class FeedListFragment extends MainListFragment { protected static final String TAG = FeedListFragment.class.getSimpleName(); protected static final TYPE THIS_TYPE = TYPE.FEED; public static final String FRAGMENT = "FEED_FRAGMENT"; public static final String FEED_CAT_ID = "FEED_CAT_ID"; public static final String FEED_CAT_TITLE = "FEED_CAT_TITLE"; private static final int MARK_GROUP = 300; private static final int MARK_READ = MARK_GROUP + 1; private static final int UNSUBSCRIBE = MARK_GROUP + 2; // Extras private int categoryId; private Uri feedUri; public static FeedListFragment newInstance(int id) { // Create a new fragment instance FeedListFragment detail = new FeedListFragment(); detail.categoryId = id; detail.setRetainInstance(true); return detail; } @Override public void onCreate(Bundle instance) { Controller.getInstance().lastOpenedFeeds.clear(); if (instance != null) categoryId = instance.getInt(FEED_CAT_ID); setHasOptionsMenu(true); super.onCreate(instance); } @Override public void onActivityCreated(Bundle instance) { adapter = new FeedAdapter(getActivity()); getLoaderManager().restartLoader(TYPE_FEED_ID, null, this); super.onActivityCreated(instance); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(FEED_CAT_ID, categoryId); super.onSaveInstanceState(outState); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkRead); menu.add(MARK_GROUP, UNSUBSCRIBE, Menu.NONE, R.string.Subscribe_unsubscribe); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); if (cmi == null) return false; switch (item.getItemId()) { case MARK_READ: new Updater(getActivity(), new ReadStateUpdater(adapter.getId(cmi.position), 42)).exec(); return true; case UNSUBSCRIBE: YesNoUpdaterDialog dialog = YesNoUpdaterDialog.getInstance( new UnsubscribeUpdater(adapter.getId(cmi.position)), R.string.Dialog_unsubscribeTitle, R.string.Dialog_unsubscribeText); dialog.show(getFragmentManager(), YesNoUpdaterDialog.DIALOG); return true; } return false; } @Override public TYPE getType() { return THIS_TYPE; } public int getCategoryId() { return categoryId; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == TYPE_FEED_ID) { Builder builder = ListContentProvider.CONTENT_URI_FEED.buildUpon(); builder.appendQueryParameter(ListContentProvider.PARAM_CAT_ID, categoryId + ""); feedUri = builder.build(); return new CursorLoader(getActivity(), feedUri, null, null, null, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (loader.getId() == TYPE_FEED_ID) adapter.changeCursor(data); super.onLoadFinished(loader, data); } @Override public void onLoaderReset(Loader<Cursor> loader) { if (loader.getId() == TYPE_FEED_ID) adapter.changeCursor(null); } @Override protected void fetchOtherData() { Category category = DBHelper.getInstance().getCategory(categoryId); if (category != null) title = category.title; unreadCount = DBHelper.getInstance().getUnreadCount(categoryId, true); } @Override public void doRefresh() { // getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); Activity activity = getActivity(); if (activity != null && feedUri != null) activity.getContentResolver().notifyChange(feedUri, null); super.doRefresh(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/fragments/FeedListFragment.java
Java
gpl3
5,839
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.fragments; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.gui.interfaces.IDataChangedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.gui.view.MyGestureDetector; import org.ttrssreader.model.MainAdapter; import org.ttrssreader.utils.AsyncTask; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.ListFragment; import android.app.LoaderManager; import android.content.Loader; import android.content.res.TypedArray; import android.database.Cursor; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; public abstract class MainListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { protected static final String TAG = MainListFragment.class.getSimpleName(); protected static final int TYPE_CAT_ID = 1; protected static final int TYPE_FEED_ID = 2; protected static final int TYPE_HEADLINE_ID = 3; protected static final String SELECTED_INDEX = "selectedIndex"; protected static final int SELECTED_INDEX_DEFAULT = Integer.MIN_VALUE; protected static final String SELECTED_ID = "selectedId"; protected static final int SELECTED_ID_DEFAULT = Integer.MIN_VALUE; protected int selectedId = SELECTED_ID_DEFAULT; private int scrollPosition; protected MainAdapter adapter = null; protected GestureDetector gestureDetector; protected View.OnTouchListener gestureListener; protected String title; protected int unreadCount; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Async update of title und unread data: updateTitleAndUnread(); } @SuppressWarnings("deprecation") @Override public void onViewCreated(View view, Bundle savedInstanceState) { int[] attrs = new int[] { android.R.attr.windowBackground }; TypedArray ta = getActivity().obtainStyledAttributes(attrs); Drawable drawableFromTheme = ta.getDrawable(0); ta.recycle(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) view.setBackgroundDrawable(drawableFromTheme); else view.setBackground(drawableFromTheme); super.onViewCreated(view, savedInstanceState); } @Override public void onActivityCreated(Bundle instance) { super.onActivityCreated(instance); setListAdapter(adapter); adapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { setChecked(selectedId); super.onChanged(); } }); getListView().setSelector(R.drawable.list_item_background); registerForContextMenu(getListView()); ActionBar actionBar = getActivity().getActionBar(); gestureDetector = new GestureDetector(getActivity(), new MyGestureDetector(actionBar, Controller.getInstance() .hideActionbar()), null); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event) || v.performClick(); } }; getListView().setOnTouchListener(gestureListener); // Read the selected list item after orientation changes and similar getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (instance != null) { int selectedIndex = instance.getInt(SELECTED_INDEX, SELECTED_INDEX_DEFAULT); selectedId = adapter.getId(selectedIndex); setChecked(selectedId); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED_ID, selectedId); super.onSaveInstanceState(outState); } @Override public void onStop() { super.onStop(); getListView().setVisibility(View.GONE); } @Override public void onResume() { getListView().setVisibility(View.VISIBLE); getListView().setSelectionFromTop(scrollPosition, 0); super.onResume(); } @Override public void onPause() { super.onPause(); scrollPosition = getListView().getFirstVisiblePosition(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { int selectedIndex = position; // Set selected item selectedId = adapter.getId(selectedIndex); setChecked(selectedId); Activity activity = getActivity(); if (activity instanceof IItemSelectedListener) { ((IItemSelectedListener) activity).itemSelected(this, selectedIndex, selectedId); } } private void setChecked(int id) { int pos = -1; if (adapter != null) { for (int item : adapter.getIds()) { pos++; if (item == id) { getListView().setItemChecked(pos, true); getListView().smoothScrollToPosition(pos); return; } } } if (getListView() != null) { // Nothing found, uncheck everything: getListView().setItemChecked(getListView().getCheckedItemPosition(), false); } } public void doRefresh() { } public String getTitle() { if (title != null) return title; return ""; } public int getUnread() { if (unreadCount > 0) return unreadCount; return 0; } public abstract TYPE getType(); public static Fragment recreateFragment(FragmentManager fm, Fragment f) { try { Fragment.SavedState savedState = fm.saveFragmentInstanceState(f); Fragment newInstance = f.getClass().newInstance(); newInstance.setInitialSavedState(savedState); return newInstance; } catch (Exception e) { Log.e(TAG, "Error while recreating Fragment-Instance...", e); return null; } } public void setSelectedId(int selectedId) { this.selectedId = selectedId; setChecked(selectedId); } /** * Updates in here are started asynchronously since the DB is accessed. When the children are done with the updates * we call {@link IDataChangedListener#dataLoadingFinished()} in the UI-thread again. */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { updateTitleAndUnread(); adapter.notifyDataSetChanged(); } private volatile Boolean updateTitleAndUnreadRunning = false; private void updateTitleAndUnread() { if (!updateTitleAndUnreadRunning) { updateTitleAndUnreadRunning = true; new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... params) { fetchOtherData(); return null; } protected void onPostExecute(Void result) { if (getActivity() instanceof IDataChangedListener) ((IDataChangedListener) getActivity()).dataLoadingFinished(); updateTitleAndUnreadRunning = false; }; }.execute(); } } protected abstract void fetchOtherData(); }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/fragments/MainListFragment.java
Java
gpl3
8,529
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.fragments; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.HtmlNode; import org.htmlcleaner.TagNode; import org.htmlcleaner.TagNodeVisitor; import org.stringtemplate.v4.ST; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.ProgressBarManager; import org.ttrssreader.gui.ErrorActivity; import org.ttrssreader.gui.FeedHeadlineActivity; import org.ttrssreader.gui.TextInputAlert; import org.ttrssreader.gui.dialogs.ArticleLabelDialog; import org.ttrssreader.gui.dialogs.ImageCaptionDialog; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.gui.view.ArticleWebViewClient; import org.ttrssreader.gui.view.MyGestureDetector; import org.ttrssreader.gui.view.MyWebView; import org.ttrssreader.imageCache.ImageCache; import org.ttrssreader.model.FeedHeadlineAdapter; import org.ttrssreader.model.ListContentProvider; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.pojos.Label; import org.ttrssreader.model.pojos.RemoteFile; import org.ttrssreader.model.updaters.PublishedStateUpdater; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.StarredStateUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.DateUtils; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.Utils; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.LoaderManager; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.content.res.Configuration; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Vibrator; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebView; import android.webkit.WebView.HitTestResult; import android.widget.Button; import android.widget.FrameLayout; import android.widget.TextView; public class ArticleFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, TextInputAlertCallback { protected static final String TAG = ArticleFragment.class.getSimpleName(); public static final String FRAGMENT = "ARTICLE_FRAGMENT"; public static final String ARTICLE_ID = "ARTICLE_ID"; public static final String ARTICLE_FEED_ID = "ARTICLE_FEED_ID"; public static final String ARTICLE_MOVE = "ARTICLE_MOVE"; public static final int ARTICLE_MOVE_NONE = 0; public static final int ARTICLE_MOVE_DEFAULT = ARTICLE_MOVE_NONE; private static final int CONTEXT_MENU_SHARE_URL = 1000; private static final int CONTEXT_MENU_SHARE_ARTICLE = 1001; private static final int CONTEXT_MENU_DISPLAY_CAPTION = 1002; private static final int CONTEXT_MENU_COPY_URL = 1003; private static final char TEMPLATE_DELIMITER_START = '$'; private static final char TEMPLATE_DELIMITER_END = '$'; private static final String LABEL_COLOR_STRING = "<span style=\"color: %s; background-color: %s\">%s</span>"; private static final String TEMPLATE_ARTICLE_VAR = "article"; private static final String TEMPLATE_FEED_VAR = "feed"; private static final String MARKER_CACHED_IMAGES = "CACHED_IMAGES"; private static final String MARKER_UPDATED = "UPDATED"; private static final String MARKER_LABELS = "LABELS"; private static final String MARKER_CONTENT = "CONTENT"; private static final String MARKER_ATTACHMENTS = "ATTACHMENTS"; // Extras private int articleId = -1; private int feedId = -1; private int categoryId = Integer.MIN_VALUE; private boolean selectArticlesForCategory = false; private int lastMove = ARTICLE_MOVE_DEFAULT; private Article article = null; private Feed feed = null; private String content; private boolean linkAutoOpened; private boolean markedRead = false; private FrameLayout webContainer = null; private MyWebView webView; private boolean webviewInitialized = false; private Button buttonNext; private Button buttonPrev; private FeedHeadlineAdapter parentAdapter = null; private List<Integer> parentIds = null; private int[] parentIdsBeforeAndAfter = new int[2]; private String mSelectedExtra; private String mSelectedAltText; private ArticleJSInterface articleJSInterface; private GestureDetector gestureDetector = null; private View.OnTouchListener gestureListener = null; public static ArticleFragment newInstance(int id, int feedId, int categoryId, boolean selectArticles, int lastMove) { // Create a new fragment instance ArticleFragment detail = new ArticleFragment(); detail.articleId = id; detail.feedId = feedId; detail.categoryId = categoryId; detail.selectArticlesForCategory = selectArticles; detail.lastMove = lastMove; detail.setRetainInstance(true); return detail; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.articleitem, container, false); } @Override public void onCreate(Bundle instance) { if (instance != null) { articleId = instance.getInt(ARTICLE_ID); feedId = instance.getInt(ARTICLE_FEED_ID); categoryId = instance.getInt(FeedHeadlineListFragment.FEED_CAT_ID); selectArticlesForCategory = instance.getBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES); lastMove = instance.getInt(ARTICLE_MOVE); if (webView != null) webView.restoreState(instance); } super.onCreate(instance); } @Override public void onActivityCreated(Bundle instance) { super.onActivityCreated(instance); articleJSInterface = new ArticleJSInterface(getActivity()); parentAdapter = new FeedHeadlineAdapter(getActivity(), feedId, selectArticlesForCategory); getLoaderManager().restartLoader(MainListFragment.TYPE_HEADLINE_ID, null, this); initData(); initUI(); doRefresh(); } @Override public void onConfigurationChanged(Configuration newConfig) { // Remove the WebView from the old placeholder if (webView != null) webContainer.removeView(webView); super.onConfigurationChanged(newConfig); initUI(); doRefresh(); } @Override public void onSaveInstanceState(Bundle instance) { instance.putInt(ARTICLE_ID, articleId); instance.putInt(ARTICLE_FEED_ID, feedId); instance.putInt(FeedHeadlineListFragment.FEED_CAT_ID, categoryId); instance.putBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES, selectArticlesForCategory); instance.putInt(ARTICLE_MOVE, lastMove); if (webView != null) webView.saveState(instance); super.onSaveInstanceState(instance); } public void resetParentInformation() { parentIds.clear(); parentIdsBeforeAndAfter[0] = Integer.MIN_VALUE; parentIdsBeforeAndAfter[1] = Integer.MIN_VALUE; } private void fillParentInformation() { if (parentIds == null) { parentIds = new ArrayList<Integer>(parentAdapter.getCount() + 2); parentIds.add(Integer.MIN_VALUE); parentIds.addAll(parentAdapter.getIds()); parentIds.add(Integer.MIN_VALUE); parentAdapter.notifyDataSetInvalidated(); // Not needed anymore } // Added dummy-elements at top and bottom of list for easier access, index == 0 cannot happen. int index = -1; int i = 0; for (Integer id : parentIds) { if (id.intValue() == articleId) { index = i; break; } i++; } if (index > 0) { parentIdsBeforeAndAfter[0] = parentIds.get(index - 1); // Previous parentIdsBeforeAndAfter[1] = parentIds.get(index + 1); // Next } else { parentIdsBeforeAndAfter[0] = Integer.MIN_VALUE; parentIdsBeforeAndAfter[1] = Integer.MIN_VALUE; } } @SuppressLint("ClickableViewAccessibility") private void initUI() { // Wrap webview inside another FrameLayout to avoid memory leaks as described here: // http://stackoverflow.com/questions/3130654/memory-leak-in-webview webContainer = (FrameLayout) getActivity().findViewById(R.id.article_webView_Container); buttonPrev = (Button) getActivity().findViewById(R.id.article_buttonPrev); buttonNext = (Button) getActivity().findViewById(R.id.article_buttonNext); buttonPrev.setOnClickListener(onButtonPressedListener); buttonNext.setOnClickListener(onButtonPressedListener); // Initialize the WebView if necessary if (webView == null) { webView = new MyWebView(getActivity()); webView.setWebViewClient(new ArticleWebViewClient()); webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); boolean supportZoom = Controller.getInstance().supportZoomControls(); webView.getSettings().setSupportZoom(supportZoom); webView.getSettings().setBuiltInZoomControls(supportZoom); webView.getSettings().setDisplayZoomControls(false); webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(true); webView.setOnKeyListener(keyListener); webView.getSettings().setTextZoom(Controller.getInstance().textZoom()); webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); if (gestureDetector == null || gestureListener == null) { ActionBar actionBar = getActivity().getActionBar(); // Detect touch gestures like swipe and scroll down: gestureDetector = new GestureDetector(getActivity(), new ArticleGestureDetector(actionBar, Controller .getInstance().hideActionbar())); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { gestureDetector.onTouchEvent(event); // Call webView.onTouchEvent(event) everytime, seems to fix issues with webview not beeing // refreshed after swiping: return webView.onTouchEvent(event) || v.performClick(); } }; } // TODO: Lint-Error // "Custom view org/ttrssreader/gui/view/MyWebView has setOnTouchListener called on it but does not override performClick" webView.setOnTouchListener(gestureListener); } // TODO: Is this still necessary? int backgroundColor = Controller.getInstance().getThemeBackground(); int fontColor = Controller.getInstance().getThemeFont(); webView.setBackgroundColor(backgroundColor); if (getActivity().findViewById(R.id.article_view) instanceof ViewGroup) setBackground((ViewGroup) getActivity().findViewById(R.id.article_view), backgroundColor, fontColor); registerForContextMenu(webView); // Attach the WebView to its placeholder if (webView.getParent() != null && webView.getParent() instanceof FrameLayout) ((FrameLayout) webView.getParent()).removeAllViews(); webContainer.addView(webView); getActivity().findViewById(R.id.article_button_view).setVisibility( Controller.getInstance().showButtonsMode() == Constants.SHOW_BUTTONS_MODE_ALLWAYS ? View.VISIBLE : View.GONE); setHasOptionsMenu(true); } private void initData() { if (feedId > 0) Controller.getInstance().lastOpenedFeeds.add(feedId); Controller.getInstance().lastOpenedArticles.add(articleId); // Get article from DB article = DBHelper.getInstance().getArticle(articleId); if (article == null) { getActivity().finish(); return; } feed = DBHelper.getInstance().getFeed(article.feedId); // Mark as read if necessary, do it here because in doRefresh() it will be done several times even if you set // it to "unread" in the meantime. if (article.isUnread) { article.isUnread = false; markedRead = true; new Updater(null, new ReadStateUpdater(article, feedId, 0)).exec(); } getActivity().invalidateOptionsMenu(); // Force redraw of menu items in actionbar // Reload content on next doRefresh() webviewInitialized = false; } @Override public void onResume() { super.onResume(); getView().setVisibility(View.VISIBLE); } @Override public void onStop() { // Check again to make sure it didnt get updated and marked as unread again in the background if (!markedRead) { if (article != null && article.isUnread) new Updater(null, new ReadStateUpdater(article, feedId, 0)).exec(); } super.onStop(); getView().setVisibility(View.GONE); } @Override public void onDestroy() { // Check again to make sure it didnt get updated and marked as unread again in the background if (!markedRead) { if (article != null && article.isUnread) new Updater(null, new ReadStateUpdater(article, feedId, 0)).exec(); } super.onDestroy(); if (webContainer != null) webContainer.removeAllViews(); if (webView != null) webView.destroy(); } @SuppressLint("SetJavaScriptEnabled") private void doRefresh() { if (webView == null) return; try { ProgressBarManager.getInstance().addProgress(getActivity()); if (Controller.getInstance().workOffline() || !Controller.getInstance().loadImages()) { webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY); } else { webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); } // No need to reload everything if (webviewInitialized) return; // Check for errors if (Controller.getInstance().getConnector().hasLastError()) { Intent i = new Intent(getActivity(), ErrorActivity.class); i.putExtra(ErrorActivity.ERROR_MESSAGE, Controller.getInstance().getConnector().pullLastError()); startActivityForResult(i, ErrorActivity.ACTIVITY_SHOW_ERROR); return; } if (article.content == null) return; StringBuilder labels = new StringBuilder(); for (Label label : article.labels) { if (label.checked) { if (labels.length() > 0) labels.append(", "); String labelString = label.caption; if (label.foregroundColor != null && label.backgroundColor != null) labelString = String.format(LABEL_COLOR_STRING, label.foregroundColor, label.backgroundColor, label.caption); labels.append(labelString); } } // Load html from Controller and insert content ST contentTemplate = new ST(Controller.htmlTemplate, TEMPLATE_DELIMITER_START, TEMPLATE_DELIMITER_END); contentTemplate.add(TEMPLATE_ARTICLE_VAR, article); contentTemplate.add(TEMPLATE_FEED_VAR, feed); contentTemplate.add(MARKER_CACHED_IMAGES, getCachedImagesJS(article.id)); contentTemplate.add(MARKER_LABELS, labels.toString()); contentTemplate.add(MARKER_UPDATED, DateUtils.getDateTimeCustom(getActivity(), article.updated)); contentTemplate.add(MARKER_CONTENT, article.content); // Inject the specific code for attachments, <img> for images, http-link for Videos contentTemplate.add(MARKER_ATTACHMENTS, getAttachmentsMarkup(getActivity(), article.attachments)); webView.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(articleJSInterface, "articleController"); content = contentTemplate.render(); webView.loadDataWithBaseURL("file:///android_asset/", content, "text/html", "utf-8", null); if (!linkAutoOpened && article.content.length() < 3) { if (Controller.getInstance().openUrlEmptyArticle()) { Log.i(TAG, "Article-Content is empty, opening URL in browser"); linkAutoOpened = true; openLink(); } } // Everything did load, we dont have to do this again. webviewInitialized = true; } catch (Exception e) { Log.w(TAG, e.getClass().getSimpleName() + " in doRefresh(): " + e.getMessage() + " (" + e.getCause() + ")"); } finally { ProgressBarManager.getInstance().removeProgress(getActivity()); } } /** * Starts a new activity with the url of the current article. This should open a webbrowser in most cases. If the * url contains spaces or newline-characters it is first trim()'ed. */ public void openLink() { if (article.url == null || article.url.length() == 0) return; String url = article.url; if (article.url.contains(" ") || article.url.contains("\n")) url = url.trim(); try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } catch (ActivityNotFoundException e) { Log.e(TAG, "Couldn't find a suitable activity for the uri: " + url); } } public Article getArticle() { return article; } public int getArticleId() { return articleId; } /** * Recursively walks all viewGroups and their Views inside the given ViewGroup and sets the background to black and, * in case a TextView is found, the Text-Color to white. * * @param v * the ViewGroup to walk through */ private void setBackground(ViewGroup v, int background, int font) { v.setBackgroundColor(getResources().getColor(background)); for (int i = 0; i < v.getChildCount(); i++) { // View at index 0 seems to be this view itself. View vChild = v.getChildAt(i); if (vChild == null) continue; if (vChild instanceof TextView) ((TextView) vChild).setTextColor(font); if (vChild instanceof ViewGroup) setBackground(((ViewGroup) vChild), background, font); } } /** * generate HTML code for attachments to be shown inside article * * @param context * current context * @param attachments * collection of attachment URLs */ private static String getAttachmentsMarkup(Context context, Set<String> attachments) { StringBuilder content = new StringBuilder(); Map<String, Collection<String>> attachmentsByMimeType = FileUtils.groupFilesByMimeType(attachments); if (!attachmentsByMimeType.isEmpty()) { for (String mimeType : attachmentsByMimeType.keySet()) { Collection<String> mimeTypeUrls = attachmentsByMimeType.get(mimeType); if (!mimeTypeUrls.isEmpty()) { if (mimeType.equals(FileUtils.IMAGE_MIME)) { ST st = new ST(context.getResources().getString(R.string.ATTACHMENT_IMAGES_TEMPLATE)); st.add("items", mimeTypeUrls); content.append(st.render()); } else { ST st = new ST(context.getResources().getString(R.string.ATTACHMENT_MEDIA_TEMPLATE)); st.add("items", mimeTypeUrls); CharSequence linkText = mimeType.equals(FileUtils.AUDIO_MIME) || mimeType.equals(FileUtils.VIDEO_MIME) ? context .getText(R.string.ArticleActivity_MediaPlay) : context .getText(R.string.ArticleActivity_MediaDisplayLink); st.add("linkText", linkText); content.append(st.render()); } } } } return content.toString(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); HitTestResult result = ((WebView) v).getHitTestResult(); menu.setHeaderTitle(getResources().getString(R.string.ArticleActivity_ShareLink)); mSelectedExtra = null; mSelectedAltText = null; if (result.getType() == HitTestResult.SRC_ANCHOR_TYPE) { mSelectedExtra = result.getExtra(); menu.add(ContextMenu.NONE, CONTEXT_MENU_SHARE_URL, 2, getResources().getString(R.string.ArticleActivity_ShareURL)); menu.add(ContextMenu.NONE, CONTEXT_MENU_COPY_URL, 3, getResources().getString(R.string.ArticleActivity_CopyURL)); } if (result.getType() == HitTestResult.IMAGE_TYPE) { mSelectedAltText = getAltTextForImageUrl(result.getExtra()); if (mSelectedAltText != null) menu.add(ContextMenu.NONE, CONTEXT_MENU_DISPLAY_CAPTION, 1, getResources().getString(R.string.ArticleActivity_ShowCaption)); } menu.add(ContextMenu.NONE, CONTEXT_MENU_SHARE_ARTICLE, 10, getResources().getString(R.string.ArticleActivity_ShareArticle)); } public void onPrepareOptionsMenu(Menu menu) { if (article != null) { MenuItem read = menu.findItem(R.id.Article_Menu_MarkRead); if (read != null) { if (article.isUnread) { read.setTitle(getString(R.string.Commons_MarkRead)); read.setIcon(R.drawable.ic_menu_mark); } else { read.setTitle(getString(R.string.Commons_MarkUnread)); read.setIcon(R.drawable.ic_menu_clear_playlist); } } MenuItem publish = menu.findItem(R.id.Article_Menu_MarkPublish); if (publish != null) { if (article.isPublished) { publish.setTitle(getString(R.string.Commons_MarkUnpublish)); publish.setIcon(R.drawable.menu_published); } else { publish.setTitle(getString(R.string.Commons_MarkPublish)); publish.setIcon(R.drawable.menu_publish); } } MenuItem star = menu.findItem(R.id.Article_Menu_MarkStar); if (star != null) { if (article.isStarred) { star.setTitle(getString(R.string.Commons_MarkUnstar)); star.setIcon(R.drawable.menu_starred); } else { star.setTitle(getString(R.string.Commons_MarkStar)); star.setIcon(R.drawable.ic_menu_star); } } } } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.Article_Menu_MarkRead: { if (article != null) new Updater(getActivity(), new ReadStateUpdater(article, article.feedId, article.isUnread ? 0 : 1)) .exec(); return true; } case R.id.Article_Menu_MarkStar: { if (article != null) new Updater(getActivity(), new StarredStateUpdater(article, article.isStarred ? 0 : 1)).exec(); return true; } case R.id.Article_Menu_MarkPublish: { if (article != null) new Updater(getActivity(), new PublishedStateUpdater(article, article.isPublished ? 0 : 1)).exec(); return true; } case R.id.Article_Menu_MarkPublishNote: { new TextInputAlert(this, article).show(getActivity()); return true; } case R.id.Article_Menu_AddArticleLabel: { if (article != null) { DialogFragment dialog = ArticleLabelDialog.newInstance(article.id); dialog.show(getFragmentManager(), "Edit Labels"); } return true; } case R.id.Article_Menu_ShareLink: { if (article != null) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, article.url); i.putExtra(Intent.EXTRA_SUBJECT, article.title); startActivity(Intent.createChooser(i, (String) getText(R.string.ArticleActivity_ShareTitle))); } return true; } default: return false; } } /** * Using a small html parser with a visitor which goes through the html I extract the alt-attribute from the * content. If nothing is found it is left as null and the menu should'nt contain the item to display the caption. * * @param extra * the * @return the alt-text or null if none was found. */ private String getAltTextForImageUrl(String extra) { if (content == null || !content.contains(extra)) return null; HtmlCleaner cleaner = new HtmlCleaner(); TagNode node = cleaner.clean(content); MyTagNodeVisitor tnv = new MyTagNodeVisitor(extra); node.traverse(tnv); return tnv.alt; } /** * Create javascript associative array with article cached image url as key and image hash as value. Only * RemoteFiles which are "cached" are added to this array so if an image is not available locally it is left as it * is. * * @param id * article ID * * @return javascript associative array content as text */ private String getCachedImagesJS(int id) { StringBuilder hashes = new StringBuilder(""); Collection<RemoteFile> rfs = DBHelper.getInstance().getRemoteFiles(id); if (rfs != null && !rfs.isEmpty()) { for (RemoteFile rf : rfs) { if (rf.cached) { if (hashes.length() > 0) hashes.append(",\n"); hashes.append("'"); hashes.append(rf.url); hashes.append("': '"); hashes.append(ImageCache.getHashForKey(rf.url)); hashes.append("'"); } } } return hashes.toString(); } /** * This is necessary to iterate over all HTML-Nodes and scan for images with ALT-Attributes. */ class MyTagNodeVisitor implements TagNodeVisitor { public String alt = null; private String extra; public MyTagNodeVisitor(String extra) { this.extra = extra; } public boolean visit(TagNode tagNode, HtmlNode htmlNode) { if (htmlNode instanceof TagNode) { TagNode tag = (TagNode) htmlNode; String tagName = tag.getName(); // Only if the image-url is the same as the url of the image the long-press was on: if ("img".equals(tagName) && extra.equals(tag.getAttributeByName("src"))) { alt = tag.getAttributeByName("alt"); if (alt != null) return false; } } return true; } }; @Override public boolean onContextItemSelected(android.view.MenuItem item) { Intent shareIntent = null; switch (item.getItemId()) { case CONTEXT_MENU_SHARE_URL: if (mSelectedExtra != null) { shareIntent = getUrlShareIntent(mSelectedExtra); startActivity(Intent.createChooser(shareIntent, "Share URL")); } break; case CONTEXT_MENU_COPY_URL: if (mSelectedExtra != null) { ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService( Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("URL from TTRSS", mSelectedExtra); clipboard.setPrimaryClip(clip); } break; case CONTEXT_MENU_DISPLAY_CAPTION: ImageCaptionDialog fragment = ImageCaptionDialog.getInstance(mSelectedAltText); fragment.show(getFragmentManager(), ImageCaptionDialog.DIALOG_CAPTION); return true; case CONTEXT_MENU_SHARE_ARTICLE: // default behavior is to share the article URL shareIntent = getUrlShareIntent(article.url); startActivity(Intent.createChooser(shareIntent, "Share URL")); break; } return super.onContextItemSelected(item); } private Intent getUrlShareIntent(String url) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL"); i.putExtra(Intent.EXTRA_TEXT, url); return i; } private OnClickListener onButtonPressedListener = new OnClickListener() { @Override public void onClick(View v) { if (v.equals(buttonNext)) { FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(-1); } else if (v.equals(buttonPrev)) { FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(1); } } }; private OnKeyListener keyListener = new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_N) { FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(-1); return true; } else if (keyCode == KeyEvent.KEYCODE_B) { FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(1); return true; } } return false; } }; public int openNextArticle(int direction) { int id = direction < 0 ? parentIdsBeforeAndAfter[0] : parentIdsBeforeAndAfter[1]; if (id == Integer.MIN_VALUE) { ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); return feedId; } articleId = id; lastMove = direction; fillParentInformation(); // Find next id in this direction and see if there is another next article or not id = direction < 0 ? parentIdsBeforeAndAfter[0] : parentIdsBeforeAndAfter[1]; if (id == Integer.MIN_VALUE) ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); initData(); doRefresh(); return articleId; } public void openArticle(int articleId, int feedId, int categoryId, boolean selectArticlesForCategory, int lastMove) { if (articleId == Integer.MIN_VALUE) { ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); return; } this.articleId = articleId; this.feedId = feedId; this.categoryId = categoryId; this.selectArticlesForCategory = selectArticlesForCategory; this.lastMove = lastMove; parentAdapter = new FeedHeadlineAdapter(getActivity(), feedId, selectArticlesForCategory); getLoaderManager().restartLoader(MainListFragment.TYPE_HEADLINE_ID, null, this); initData(); doRefresh(); } /** * this class represents an object, which methods can be called from article's {@code WebView} javascript to * manipulate the article activity */ public class ArticleJSInterface { /** * current article activity */ Activity activity; /** * public constructor, which saves calling activity as member variable * * @param aa * current article activity */ public ArticleJSInterface(Activity aa) { activity = aa; } /** * go to previous article */ @JavascriptInterface public void prev() { Log.d(TAG, "JS: PREV"); activity.runOnUiThread(new Runnable() { public void run() { Log.d(TAG, "JS: PREV"); FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(-1); } }); } /** * go to next article */ @JavascriptInterface public void next() { Log.d(TAG, "JS: NEXT"); activity.runOnUiThread(new Runnable() { public void run() { Log.d(TAG, "JS: NEXT"); FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(1); } }); } } class ArticleGestureDetector extends MyGestureDetector { public ArticleGestureDetector(ActionBar actionBar, boolean hideActionbar) { super(actionBar, hideActionbar); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // Refresh metrics-data in Controller Controller.refreshDisplayMetrics(((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay()); if (Math.abs(e1.getY() - e2.getY()) > Controller.relSwipeMaxOffPath) return false; if (e1.getX() - e2.getX() > Controller.relSwipeMinDistance && Math.abs(velocityX) > Controller.relSwipteThresholdVelocity) { // right to left swipe FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(1); return true; } else if (e2.getX() - e1.getX() > Controller.relSwipeMinDistance && Math.abs(velocityX) > Controller.relSwipteThresholdVelocity) { // left to right swipe FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(-1); return true; } return false; } }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == MainListFragment.TYPE_HEADLINE_ID) { Builder builder = ListContentProvider.CONTENT_URI_HEAD.buildUpon(); builder.appendQueryParameter(ListContentProvider.PARAM_CAT_ID, categoryId + ""); builder.appendQueryParameter(ListContentProvider.PARAM_FEED_ID, feedId + ""); builder.appendQueryParameter(ListContentProvider.PARAM_SELECT_FOR_CAT, (selectArticlesForCategory ? "1" : "0")); return new CursorLoader(getActivity(), builder.build(), null, null, null, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (loader.getId() == MainListFragment.TYPE_HEADLINE_ID) { parentAdapter.changeCursor(data); fillParentInformation(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { if (loader.getId() == MainListFragment.TYPE_HEADLINE_ID) parentAdapter.changeCursor(null); } @Override public void onPublishNoteResult(Article a, String note) { new Updater(getActivity(), new PublishedStateUpdater(a, a.isPublished ? 0 : 1, note)).exec(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/fragments/ArticleFragment.java
Java
gpl3
39,859
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.fragments; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.CategoryActivity; import org.ttrssreader.gui.FeedHeadlineActivity; import org.ttrssreader.gui.dialogs.YesNoUpdaterDialog; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.model.CategoryAdapter; import org.ttrssreader.model.ListContentProvider; import org.ttrssreader.model.updaters.IUpdatable; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.Updater; import android.app.Activity; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; public class CategoryListFragment extends MainListFragment { protected static final String TAG = CategoryListFragment.class.getSimpleName(); protected static final TYPE THIS_TYPE = TYPE.CATEGORY; public static final String FRAGMENT = "CATEGORY_FRAGMENT"; private static final int MARK_GROUP = 100; private static final int MARK_READ = MARK_GROUP + 1; private static final int SELECT_ARTICLES = MARK_GROUP + 2; private static final int SELECT_FEEDS = MARK_GROUP + 3; private Uri categoryUri; public static CategoryListFragment newInstance() { // Create a new fragment instance CategoryListFragment detail = new CategoryListFragment(); detail.setRetainInstance(true); return detail; } @Override public void onCreate(Bundle instance) { if (!Controller.isTablet) Controller.getInstance().lastOpenedFeeds.clear(); Controller.getInstance().lastOpenedArticles.clear(); setHasOptionsMenu(true); super.onCreate(instance); } @Override public void onActivityCreated(Bundle instance) { adapter = new CategoryAdapter(getActivity()); getLoaderManager().restartLoader(TYPE_CAT_ID, null, this); super.onActivityCreated(instance); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkRead); if (Controller.getInstance().invertBrowsing()) menu.add(MARK_GROUP, SELECT_FEEDS, Menu.NONE, R.string.Commons_SelectFeeds); else menu.add(MARK_GROUP, SELECT_ARTICLES, Menu.NONE, R.string.Commons_SelectArticles); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); if (cmi == null) return false; int id = adapter.getId(cmi.position); switch (item.getItemId()) { case MARK_READ: if (id < -10) new Updater(getActivity(), new ReadStateUpdater(id, 42)).exec(); new Updater(getActivity(), new ReadStateUpdater(id)).exec(); return true; case SELECT_ARTICLES: if (id < 0) return false; if (getActivity() instanceof CategoryActivity) ((CategoryActivity) getActivity()).displayHeadlines(FeedHeadlineActivity.FEED_NO_ID, id, true); return true; case SELECT_FEEDS: if (id < 0) return false; if (getActivity() instanceof CategoryActivity) ((CategoryActivity) getActivity()).displayFeed(id); return true; } return false; } @Override public void onPrepareOptionsMenu(Menu menu) { if (!Controller.isTablet && selectedId != Integer.MIN_VALUE) menu.removeItem(R.id.Menu_MarkAllRead); if (selectedId == Integer.MIN_VALUE) menu.removeItem(R.id.Menu_MarkFeedsRead); super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case R.id.Menu_MarkAllRead: { boolean backAfterUpdate = Controller.getInstance().goBackAfterMarkAllRead(); IUpdatable updater = new ReadStateUpdater(ReadStateUpdater.TYPE.ALL_CATEGORIES); YesNoUpdaterDialog dialog = YesNoUpdaterDialog.getInstance(updater, R.string.Dialog_Title, R.string.Dialog_MarkAllRead, backAfterUpdate); dialog.show(getFragmentManager(), YesNoUpdaterDialog.DIALOG); return true; } case R.id.Menu_MarkFeedsRead: if (selectedId > Integer.MIN_VALUE) { boolean backAfterUpdate = Controller.getInstance().goBackAfterMarkAllRead(); IUpdatable updateable = new ReadStateUpdater(selectedId); YesNoUpdaterDialog dialog = YesNoUpdaterDialog.getInstance(updateable, R.string.Dialog_Title, R.string.Dialog_MarkFeedsRead, backAfterUpdate); dialog.show(getFragmentManager(), YesNoUpdaterDialog.DIALOG); } return true; default: return false; } } @Override public TYPE getType() { return THIS_TYPE; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == TYPE_CAT_ID) { Builder builder = ListContentProvider.CONTENT_URI_CAT.buildUpon(); categoryUri = builder.build(); return new CursorLoader(getActivity(), categoryUri, null, null, null, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (loader.getId() == TYPE_CAT_ID) adapter.changeCursor(data); super.onLoadFinished(loader, data); } @Override public void onLoaderReset(Loader<Cursor> loader) { if (loader.getId() == TYPE_CAT_ID) adapter.changeCursor(null); } @Override protected void fetchOtherData() { title = "TTRSS-Reader"; // Hardcoded since this does not change and we would need to be attached to an activity // here to be able to read from the ressources. unreadCount = DBHelper.getInstance().getUnreadCount(Data.VCAT_ALL, true); } @Override public void doRefresh() { // getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); Activity activity = getActivity(); if (activity != null && categoryUri != null) activity.getContentResolver().notifyChange(categoryUri, null); super.doRefresh(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/fragments/CategoryListFragment.java
Java
gpl3
7,813
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.dialogs; import org.ttrssreader.R; import org.ttrssreader.model.updaters.IUpdatable; import org.ttrssreader.model.updaters.Updater; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; public class YesNoUpdaterDialog extends MyDialogFragment { public static final String DIALOG = "yesnodialog"; private IUpdatable updater; private int titleRes; private int msgRes; private boolean backAfterUpdate; public static YesNoUpdaterDialog getInstance(IUpdatable updater, int titleRes, int msgRes) { return getInstance(updater, titleRes, msgRes, false); } public static YesNoUpdaterDialog getInstance(IUpdatable updater, int titleRes, int msgRes, boolean backAfterUpdate) { YesNoUpdaterDialog fragment = new YesNoUpdaterDialog(); fragment.updater = updater; fragment.titleRes = titleRes; fragment.msgRes = msgRes; fragment.backAfterUpdate = backAfterUpdate; return fragment; } @Override public void onCreate(Bundle instance) { super.onCreate(instance); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(titleRes)); builder.setMessage(getResources().getString(msgRes)); builder.setPositiveButton(getResources().getString(R.string.Yes), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { new Updater(getActivity(), updater, backAfterUpdate).exec(); d.dismiss(); } }); builder.setNegativeButton(getResources().getString(R.string.No), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { d.dismiss(); } }); return builder.create(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/dialogs/YesNoUpdaterDialog.java
Java
gpl3
2,721
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.dialogs; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; public class ErrorDialog extends MyDialogFragment { Context context; String message; public static ErrorDialog getInstance(Context context, String message) { ErrorDialog dialog = new ErrorDialog(); dialog.context = context; dialog.message = message; return dialog; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("Error"); alertDialogBuilder.setMessage(message); alertDialogBuilder.setNeutralButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return alertDialogBuilder.create(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/dialogs/ErrorDialog.java
Java
gpl3
1,589
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.dialogs; import android.app.DialogFragment; import android.os.Bundle; public class MyDialogFragment extends DialogFragment { @Override public void onCreate(Bundle instance) { super.onCreate(instance); setRetainInstance(true); } @Override public void onDestroyView() { // See http://stackoverflow.com/a/15444485 if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/dialogs/MyDialogFragment.java
Java
gpl3
1,063
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.dialogs; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.controllers.Data; import org.ttrssreader.model.pojos.Label; import org.ttrssreader.model.updaters.IUpdatable; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.LabelTitleComparator; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.TextView; public class ArticleLabelDialog extends MyDialogFragment { public static final String PARAM_ARTICLE_ID = "article_id"; private int articleId; private List<Label> labels; private View view; private LinearLayout labelsView; public static ArticleLabelDialog newInstance(int articleId) { ArticleLabelDialog frag = new ArticleLabelDialog(); Bundle args = new Bundle(); args.putInt(PARAM_ARTICLE_ID, articleId); frag.setArguments(args); return frag; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle extras = getArguments(); if (extras != null) { articleId = extras.getInt(PARAM_ARTICLE_ID); } else if (savedInstanceState != null) { articleId = savedInstanceState.getInt(PARAM_ARTICLE_ID); } // Put labels into list and sort by caption: labels = new ArrayList<Label>(); for (Label label : Data.getInstance().getLabels(articleId)) { labels.add(label); } Collections.sort(labels, LabelTitleComparator.LABELTITLE_COMPARATOR); for (Label label : labels) { CheckBox checkbox = new CheckBox(getActivity()); checkbox.setId(label.id); checkbox.setText(label.caption); checkbox.setChecked(label.checked); checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView instanceof CheckBox) { CheckBox cb = (CheckBox) buttonView; for (Label label : labels) { if (label.id == cb.getId()) { label.checked = isChecked; label.checkedChanged = !label.checkedChanged; break; } } } } }); labelsView.addView(checkbox); } if (labels.size() == 0) { TextView tv = new TextView(getActivity()); tv.setText(R.string.Labels_NoLabels); labelsView.addView(tv); } } @SuppressLint("InflateParams") @Override public Dialog onCreateDialog(Bundle args) { // AboutDialog benutzt als Schriftfarbe automatisch die invertierte Hintergrundfarbe AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AboutDialog)); LayoutInflater inflater = getActivity().getLayoutInflater(); view = inflater.inflate(R.layout.articlelabeldialog, null); builder.setView(view).setPositiveButton(R.string.Utils_OkayAction, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { new Updater(null, new ArticleLabelUpdater()).execute(); getActivity().setResult(Activity.RESULT_OK); dismiss(); } }).setNegativeButton(R.string.Utils_CancelAction, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { getActivity().setResult(Activity.RESULT_CANCELED); dismiss(); } }); labelsView = (LinearLayout) view.findViewById(R.id.labels); return builder.create(); } public class ArticleLabelUpdater implements IUpdatable { @Override public void update(Updater parent) { for (Label label : labels) { if (label.checkedChanged) { Data.getInstance().setLabel(articleId, label); } } } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/dialogs/ArticleLabelDialog.java
Java
gpl3
5,428
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.dialogs; import org.ttrssreader.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; public class ImageCaptionDialog extends MyDialogFragment { public static final String DIALOG_CAPTION = "image_caption"; String caption; public static ImageCaptionDialog getInstance(String caption) { ImageCaptionDialog fragment = new ImageCaptionDialog(); fragment.caption = caption; return fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(R.string.Dialog_imageCaptionTitle)); builder.setMessage(caption); builder.setNeutralButton(getResources().getString(R.string.Close), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { d.dismiss(); } }); return builder.create(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/dialogs/ImageCaptionDialog.java
Java
gpl3
1,750
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.dialogs; import org.ttrssreader.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; public class ChangelogDialog extends MyDialogFragment { public static ChangelogDialog getInstance() { return new ChangelogDialog(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(R.string.Changelog_Title)); final String[] changes = getResources().getStringArray(R.array.updates); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < changes.length; i++) { sb.append("\n\n"); sb.append(changes[i]); if (sb.length() > 4000) // Don't include all messages, nobody reads the old stuff anyway break; } builder.setMessage(sb.toString().trim()); builder.setPositiveButton(android.R.string.ok, null); builder.setNeutralButton((String) getText(R.string.CategoryActivity_Donate), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString( R.string.DonateUrl)))); d.dismiss(); } }); return builder.create(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/dialogs/ChangelogDialog.java
Java
gpl3
2,273
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui.dialogs; import org.ttrssreader.R; import org.ttrssreader.gui.PreferencesActivity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; public class WelcomeDialog extends MyDialogFragment { public static WelcomeDialog getInstance() { return new WelcomeDialog(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(R.string.Welcome_Title)); builder.setMessage(getResources().getString(R.string.Welcome_Message)); builder.setNeutralButton((String) getText(R.string.Preferences_Btn), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { Intent i = new Intent(getActivity(), PreferencesActivity.class); startActivity(i); d.dismiss(); } }); return builder.create(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/dialogs/WelcomeDialog.java
Java
gpl3
1,761
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * <http://www.apache.org/licenses/LICENSE-2.0> * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package org.ttrssreader.gui; import org.ttrssreader.controllers.Controller; import android.app.Activity; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.twofortyfouram.locale.api.R; /** * Superclass for plug-in Activities. This class takes care of initializing aspects of the plug-in's UI to * look more integrated with the plug-in host. */ public abstract class AbstractPluginActivity extends Activity { protected static final String TAG = AbstractPluginActivity.class.getSimpleName(); /** * Flag boolean that can only be set to true via the "Don't Save" * {@link com.twofortyfouram.locale.platform.R.id#twofortyfouram_locale_menu_dontsave} menu item in * {@link #onMenuItemSelected(int, MenuItem)}. */ /* * There is no need to save/restore this field's state. */ private boolean mIsCancelled = false; @Override protected void onCreate(final Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); CharSequence callingApplicationLabel = null; try { callingApplicationLabel = getPackageManager().getApplicationLabel( getPackageManager().getApplicationInfo(getCallingPackage(), 0)); } catch (final NameNotFoundException e) { Log.e(TAG, "Calling package couldn't be found", e); //$NON-NLS-1$ } if (null != callingApplicationLabel) { setTitle(callingApplicationLabel); } } @Override public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.twofortyfouram_locale_help_save_dontsave, menu); getActionBar().setDisplayHomeAsUpEnabled(true); /* * Note: There is a small TOCTOU error here, in that the host could be uninstalled right after * launching the plug-in. That would cause getApplicationIcon() to return the default application * icon. It won't fail, but it will return an incorrect icon. * * In practice, the chances that the host will be uninstalled while the plug-in UI is running are very * slim. */ try { getActionBar().setIcon(getPackageManager().getApplicationIcon(getCallingPackage())); } catch (final NameNotFoundException e) { Log.w(TAG, "An error occurred loading the host's icon", e); //$NON-NLS-1$ } return true; } @Override public boolean onMenuItemSelected(final int featureId, final MenuItem item) { final int id = item.getItemId(); if (android.R.id.home == id) { finish(); return true; } else if (R.id.twofortyfouram_locale_menu_dontsave == id) { mIsCancelled = true; finish(); return true; } else if (R.id.twofortyfouram_locale_menu_save == id) { finish(); return true; } return super.onOptionsItemSelected(item); } /** * During {@link #finish()}, subclasses can call this method to determine whether the Activity was * canceled. * * @return True if the Activity was canceled. False if the Activity was not canceled. */ protected boolean isCanceled() { return mIsCancelled; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/AbstractPluginActivity.java
Java
gpl3
4,246
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import java.io.File; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.model.HeaderAdapter; import org.ttrssreader.preferences.Constants; import org.ttrssreader.preferences.FileBrowserHelper; import org.ttrssreader.preferences.FileBrowserHelper.FileBrowserFailOverCallback; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import org.ttrssreader.utils.Utils; import android.app.backup.BackupManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ListAdapter; public class PreferencesActivity extends PreferenceActivity { protected static final String TAG = PreferencesActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); private static final String PREFS_DISPLAY = "prefs_display"; private static final String PREFS_HEADERS = "prefs_headers"; private static final String PREFS_HTTP = "prefs_http"; private static final String PREFS_MAIN_TOP = "prefs_main_top"; private static final String PREFS_SSL = "prefs_ssl"; private static final String PREFS_SYSTEM = "prefs_system"; private static final String PREFS_USAGE = "prefs_usage"; private static final String PREFS_WIFI = "prefs_wifi"; public static final int ACTIVITY_SHOW_PREFERENCES = 43; public static final int ACTIVITY_CHOOSE_ATTACHMENT_FOLDER = 1; public static final int ACTIVITY_CHOOSE_CACHE_FOLDER = 2; private static AsyncTask<Void, Void, Void> init; private static List<Header> _headers; private static Preference downloadPath; private static Preference cachePath; private static PreferenceActivity activity; private Context context; private boolean needResource = false; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); // IMPORTANT! mDamageReport.initialize(); context = getApplicationContext(); activity = this; setResult(ACTIVITY_SHOW_PREFERENCES); if (needResource) { addPreferencesFromResource(R.xml.prefs_main_top); addPreferencesFromResource(R.xml.prefs_http); addPreferencesFromResource(R.xml.prefs_ssl); addPreferencesFromResource(R.xml.prefs_wifi); addPreferencesFromResource(R.xml.prefs_usage); addPreferencesFromResource(R.xml.prefs_display); addPreferencesFromResource(R.xml.prefs_system); addPreferencesFromResource(R.xml.prefs_main_bottom); } initializePreferences(null); } @Override public void onBuildHeaders(List<Header> headers) { _headers = headers; if (onIsHidingHeaders()) { needResource = true; } else { loadHeadersFromResource(R.xml.prefs_headers, headers); } } @Override public void setListAdapter(ListAdapter adapter) { if (adapter == null) { super.setListAdapter(null); } else { super.setListAdapter(new HeaderAdapter(this, _headers)); } } @SuppressWarnings("deprecation") private static void initializePreferences(PreferenceFragment fragment) { if (fragment != null) { downloadPath = fragment.findPreference(Constants.SAVE_ATTACHMENT); cachePath = fragment.findPreference(Constants.CACHE_FOLDER); } else { downloadPath = activity.findPreference(Constants.SAVE_ATTACHMENT); cachePath = activity.findPreference(Constants.CACHE_FOLDER); } if (downloadPath != null) { downloadPath.setSummary(Controller.getInstance().saveAttachmentPath()); downloadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FileBrowserHelper.getInstance().showFileBrowserActivity(activity, new File(Controller.getInstance().saveAttachmentPath()), ACTIVITY_CHOOSE_ATTACHMENT_FOLDER, callbackDownloadPath); return true; } FileBrowserFailOverCallback callbackDownloadPath = new FileBrowserFailOverCallback() { @Override public void onPathEntered(String path) { downloadPath.setSummary(path); Controller.getInstance().setSaveAttachmentPath(path); } @Override public void onCancel() { } }; }); } if (cachePath != null) { cachePath.setSummary(Controller.getInstance().cacheFolder()); cachePath.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FileBrowserHelper.getInstance().showFileBrowserActivity(activity, new File(Controller.getInstance().cacheFolder()), ACTIVITY_CHOOSE_CACHE_FOLDER, callbackCachePath); return true; } FileBrowserFailOverCallback callbackCachePath = new FileBrowserFailOverCallback() { @Override public void onPathEntered(String path) { cachePath.setSummary(path); Controller.getInstance().setCacheFolder(path); } @Override public void onCancel() { } }; }); } } @Override protected void onPause() { super.onPause(); PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener( Controller.getInstance()); } @Override protected void onResume() { super.onResume(); PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener( Controller.getInstance()); } @Override protected void onStop() { super.onStop(); if (init != null) { init.cancel(true); init = null; } if (!Utils.checkIsConfigInvalid()) { init = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { Controller.getInstance().checkAndInitializeController(context, null); return null; } }; init.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } if (Controller.getInstance().isPreferencesChanged()) { new BackupManager(this).dataChanged(); Controller.getInstance().setPreferencesChanged(false); } } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = this.getMenuInflater(); inflater.inflate(R.menu.preferences, menu); return true; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { ComponentName comp = new ComponentName(this.getPackageName(), getClass().getName()); switch (item.getItemId()) { case R.id.Preferences_Menu_Reset: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Constants.resetPreferences(prefs); this.finish(); startActivity(new Intent().setComponent(comp)); return true; case R.id.Preferences_Menu_ResetDatabase: Controller.getInstance().setDeleteDBScheduled(true); DBHelper.getInstance().checkAndInitializeDB(this); this.finish(); startActivity(new Intent().setComponent(comp)); return true; } return false; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String path = null; if (resultCode == RESULT_OK && data != null) { // obtain the filename Uri fileUri = data.getData(); if (fileUri != null) path = fileUri.getPath(); } if (path != null) { switch (requestCode) { case ACTIVITY_CHOOSE_ATTACHMENT_FOLDER: downloadPath.setSummary(path); Controller.getInstance().setSaveAttachmentPath(path); break; case ACTIVITY_CHOOSE_CACHE_FOLDER: cachePath.setSummary(path); Controller.getInstance().setCacheFolder(path); break; } } super.onActivityResult(requestCode, resultCode, data); } public static class PreferencesFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String cat = getArguments().getString("cat"); if (PREFS_DISPLAY.equals(cat)) addPreferencesFromResource(R.xml.prefs_display); if (PREFS_HEADERS.equals(cat)) addPreferencesFromResource(R.xml.prefs_headers); if (PREFS_HTTP.equals(cat)) addPreferencesFromResource(R.xml.prefs_http); if (PREFS_MAIN_TOP.equals(cat)) addPreferencesFromResource(R.xml.prefs_main_top); if (PREFS_SSL.equals(cat)) addPreferencesFromResource(R.xml.prefs_ssl); if (PREFS_SYSTEM.equals(cat)) { addPreferencesFromResource(R.xml.prefs_system); initializePreferences(this); // Manually initialize Listeners for Download- and CachePath } if (PREFS_USAGE.equals(cat)) addPreferencesFromResource(R.xml.prefs_usage); if (PREFS_WIFI.equals(cat)) addPreferencesFromResource(R.xml.prefs_wifi); } } @Override protected boolean isValidFragment(String fragmentName) { if (PreferencesFragment.class.getName().equals(fragmentName)) return true; return false; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/PreferencesActivity.java
Java
gpl3
12,171
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ErrorActivity extends Activity { protected static final String TAG = ErrorActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); public static final int ACTIVITY_SHOW_ERROR = 42; public static final int ACTIVITY_EXIT = 40; public static final String ERROR_MESSAGE = "ERROR_MESSAGE"; private String message; @Override protected void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); mDamageReport.initialize(); setContentView(R.layout.error); Bundle extras = getIntent().getExtras(); if (extras != null) { message = extras.getString(ERROR_MESSAGE); } else if (savedInstanceState != null) { message = savedInstanceState.getString(ERROR_MESSAGE); } TextView errorText = (TextView) this.findViewById(R.id.ErrorActivity_ErrorMessage); errorText.setText(message); Button prefBtn = (Button) this.findViewById(R.id.Preferences_Btn); prefBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { finish(); openPreferences(); } }); Button exitBtn = (Button) this.findViewById(R.id.ErrorActivity_ExitBtn); exitBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { exitButtonPressed(); } }); Button closeBtn = (Button) this.findViewById(R.id.ErrorActivity_CloseBtn); closeBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { closeButtonPressed(); } }); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } private void exitButtonPressed() { setResult(ACTIVITY_EXIT); finish(); } private void closeButtonPressed() { setResult(ACTIVITY_SHOW_ERROR); finish(); } private void openPreferences() { startActivity(new Intent(this, PreferencesActivity.class)); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/ErrorActivity.java
Java
gpl3
3,324
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import java.util.ArrayList; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.ProgressBarManager; import org.ttrssreader.gui.fragments.MainListFragment; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.net.JSONConnector.SubscriptionResponse; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import org.ttrssreader.utils.Utils; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; public class SubscribeActivity extends MenuActivity { protected static final String TAG = SubscribeActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); private static final String PARAM_FEEDURL = "feed_url"; private Button okButton; private Button feedPasteButton; private EditText feedUrl; private ArrayAdapter<Category> categoriesAdapter; private Spinner categorieSpinner; private ProgressDialog progress; @Override public void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); mDamageReport.initialize(); setContentView(R.layout.feedsubscribe); setTitle(R.string.IntentSubscribe); ProgressBarManager.getInstance().addProgress(activity); setProgressBarVisibility(true); String urlValue = getIntent().getStringExtra(Intent.EXTRA_TEXT); if (savedInstanceState != null) { urlValue = savedInstanceState.getString(PARAM_FEEDURL); } feedUrl = (EditText) findViewById(R.id.subscribe_url); feedUrl.setText(urlValue); categoriesAdapter = new SimpleCategoryAdapter(context); categoriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); categorieSpinner = (Spinner) findViewById(R.id.subscribe_categories); categorieSpinner.setAdapter(categoriesAdapter); SubscribeCategoryUpdater categoryUpdater = new SubscribeCategoryUpdater(); categoryUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); okButton = (Button) findViewById(R.id.subscribe_ok_button); okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progress = ProgressDialog.show(context, null, "Sending..."); new MyPublisherTask().execute(); } }); feedPasteButton = (Button) findViewById(R.id.subscribe_paste); feedPasteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String url = Utils.getTextFromClipboard(activity); String text = feedUrl.getText() != null ? feedUrl.getText().toString() : ""; int start = feedUrl.getSelectionStart(); int end = feedUrl.getSelectionEnd(); // Insert text at current position, replace text if selected text = text.substring(0, start) + url + text.substring(end, text.length()); feedUrl.setText(text); feedUrl.setSelection(end); } }); } @Override protected void onResume() { super.onResume(); // Enable/Disable Paste-Button: feedPasteButton.setEnabled(Utils.clipboardHasText(this)); doRefresh(); } @Override public void onSaveInstanceState(Bundle out) { super.onSaveInstanceState(out); EditText url = (EditText) findViewById(R.id.subscribe_url); out.putString(PARAM_FEEDURL, url.getText().toString()); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } public class MyPublisherTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { try { if (Controller.getInstance().workOffline()) { showErrorDialog(getResources().getString(R.string.SubscribeActivity_offline)); return null; } String urlValue = feedUrl.getText().toString(); int category = (int) categorieSpinner.getSelectedItemId(); if (!Utils.validateURL(urlValue)) { showErrorDialog(getResources().getString(R.string.SubscribeActivity_invalidUrl)); return null; } SubscriptionResponse ret = Data.getInstance().feedSubscribe(urlValue, category); String message = "\n\n(" + ret.message + ")"; if (ret.code == 0) showErrorDialog(getResources().getString(R.string.SubscribeActivity_invalidUrl)); if (ret.code == 1) finish(); else if (Controller.getInstance().getConnector().hasLastError()) showErrorDialog(Controller.getInstance().getConnector().pullLastError()); else if (ret.code == 2) showErrorDialog(getResources().getString(R.string.SubscribeActivity_invalidUrl) + " " + message); else if (ret.code == 3) showErrorDialog(getResources().getString(R.string.SubscribeActivity_contentIsHTML) + " " + message); else if (ret.code == 4) showErrorDialog(getResources().getString(R.string.SubscribeActivity_multipleFeeds) + " " + message); else if (ret.code == 5) showErrorDialog(getResources().getString(R.string.SubscribeActivity_cannotDownload) + " " + message); else showErrorDialog(String.format(getResources().getString(R.string.SubscribeActivity_errorCode), ret.code) + " " + message); } catch (Exception e) { showErrorDialog(e.getMessage()); } finally { progress.dismiss(); } return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (super.onCreateOptionsMenu(menu)) { menu.removeItem(R.id.Menu_Refresh); menu.removeItem(R.id.Menu_MarkAllRead); menu.removeItem(R.id.Menu_MarkFeedsRead); menu.removeItem(R.id.Menu_MarkFeedRead); menu.removeItem(R.id.Menu_FeedSubscribe); menu.removeItem(R.id.Menu_FeedUnsubscribe); menu.removeItem(R.id.Menu_DisplayOnlyUnread); menu.removeItem(R.id.Menu_InvertSort); } return true; } class SimpleCategoryAdapter extends ArrayAdapter<Category> { public SimpleCategoryAdapter(Context context) { super(context, android.R.layout.simple_list_item_1); } @Override public View getView(int position, View convertView, ViewGroup parent) { return initView(position, convertView); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return initView(position, convertView); } private View initView(int position, View convertView) { if (convertView == null) convertView = View.inflate(getContext(), android.R.layout.simple_list_item_1, null); TextView tvText1 = (TextView) convertView.findViewById(android.R.id.text1); tvText1.setText(getItem(position).title); return convertView; } } // Fill the adapter for the spinner in the background to avoid direct DB-access class SubscribeCategoryUpdater extends AsyncTask<Void, Integer, Void> { ArrayList<Category> catList = null; @Override protected Void doInBackground(Void... params) { catList = new ArrayList<Category>(DBHelper.getInstance().getAllCategories()); publishProgress(0); return null; } @Override protected void onProgressUpdate(Integer... values) { if (catList != null && !catList.isEmpty()) categoriesAdapter.addAll(catList); ProgressBarManager.getInstance().removeProgress(activity); setProgressBarVisibility(false); } } // @formatter:off // Not needed here: @Override public void itemSelected(MainListFragment source, int selectedIndex, int selectedId) { } @Override protected void doUpdate(boolean forceUpdate) { } // @formatter:on }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/SubscribeActivity.java
Java
gpl3
9,944
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import java.util.LinkedHashSet; import java.util.Set; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.dialogs.ChangelogDialog; import org.ttrssreader.gui.dialogs.WelcomeDialog; import org.ttrssreader.gui.fragments.CategoryListFragment; import org.ttrssreader.gui.fragments.FeedHeadlineListFragment; import org.ttrssreader.gui.fragments.FeedListFragment; import org.ttrssreader.gui.fragments.MainListFragment; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.Utils; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class CategoryActivity extends MenuActivity implements IItemSelectedListener { protected static final String TAG = CategoryActivity.class.getSimpleName(); private static final String DIALOG_WELCOME = "welcome"; private static final String DIALOG_UPDATE = "update"; private static final int SELECTED_VIRTUAL_CATEGORY = 1; private static final int SELECTED_CATEGORY = 2; private static final int SELECTED_LABEL = 3; private boolean cacherStarted = false; private CategoryUpdater categoryUpdater = null; private static final String SELECTED = "SELECTED"; private int selectedCategoryId = Integer.MIN_VALUE; private CategoryListFragment categoryFragment; private FeedListFragment feedFragment; @Override protected void onCreate(Bundle instance) { // Only needed to debug ANRs: // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectCustomSlowCalls().detectDiskReads() // .detectDiskWrites().detectNetwork().penaltyLog().penaltyLog().build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() // .detectLeakedClosableObjects().penaltyLog().build()); super.onCreate(instance); setContentView(R.layout.main); super.initTabletLayout(); Bundle extras = getIntent().getExtras(); if (extras != null) { selectedCategoryId = extras.getInt(SELECTED, Integer.MIN_VALUE); } else if (instance != null) { selectedCategoryId = instance.getInt(SELECTED, Integer.MIN_VALUE); } FragmentManager fm = getFragmentManager(); categoryFragment = (CategoryListFragment) fm.findFragmentByTag(CategoryListFragment.FRAGMENT); feedFragment = (FeedListFragment) fm.findFragmentByTag(FeedListFragment.FRAGMENT); if (categoryFragment == null) { categoryFragment = CategoryListFragment.newInstance(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.frame_main, categoryFragment, CategoryListFragment.FRAGMENT); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } if (Utils.checkIsFirstRun(this)) { WelcomeDialog.getInstance().show(fm, DIALOG_WELCOME); } else if (Utils.checkIsNewVersion(this)) { ChangelogDialog.getInstance().show(fm, DIALOG_UPDATE); } else if (Utils.checkIsConfigInvalid()) { // Check if we have a server specified openConnectionErrorDialog((String) getText(R.string.CategoryActivity_NoServer)); } // Start caching if requested if (Controller.getInstance().cacheImagesOnStartup()) { boolean startCache = true; if (Controller.getInstance().cacheImagesOnlyWifi()) { // Check if Wifi is connected, if not don't start the ImageCache ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!mWifi.isConnected()) { Log.i(TAG, "Preference Start ImageCache only on WIFI set, doing nothing..."); startCache = false; } } // Indicate that the cacher started anyway so the refresh is supressed if the ImageCache is configured but // only for Wifi. cacherStarted = true; if (startCache) { Log.i(TAG, "Starting ImageCache..."); doCache(false); // images } } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED, selectedCategoryId); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle instance) { selectedCategoryId = instance.getInt(SELECTED, Integer.MIN_VALUE); super.onRestoreInstanceState(instance); } @Override public void dataLoadingFinished() { setTitleAndUnread(); } @Override protected void doRefresh() { super.doRefresh(); if (categoryFragment != null) categoryFragment.doRefresh(); if (feedFragment != null) feedFragment.doRefresh(); setTitleAndUnread(); } private void setTitleAndUnread() { // Title and unread information: if (feedFragment != null) { setTitle(feedFragment.getTitle()); setUnread(feedFragment.getUnread()); } else if (categoryFragment != null) { setTitle(categoryFragment.getTitle()); setUnread(categoryFragment.getUnread()); } } @Override protected void doUpdate(boolean forceUpdate) { // Only update if no categoryUpdater already running if (categoryUpdater != null) { if (categoryUpdater.getStatus().equals(AsyncTask.Status.FINISHED)) { categoryUpdater = null; } else { return; } } if ((!isCacherRunning() && !cacherStarted) || forceUpdate) { categoryUpdater = new CategoryUpdater(forceUpdate); categoryUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean ret = super.onPrepareOptionsMenu(menu); menu.removeItem(R.id.Menu_MarkFeedRead); return ret; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case R.id.Menu_Refresh: { doUpdate(true); return true; } default: return false; } } /** * This does a full update including all labels, feeds, categories and all articles. */ public class CategoryUpdater extends ActivityUpdater { private static final int DEFAULT_TASK_COUNT = 4; public CategoryUpdater(boolean forceUpdate) { super(forceUpdate); } @Override protected Void doInBackground(Void... params) { boolean onlyUnreadArticles = Controller.getInstance().onlyUnread(); Set<Feed> labels = new LinkedHashSet<Feed>(); for (Feed f : DBHelper.getInstance().getFeeds(-2)) { if (f.unread == 0 && onlyUnreadArticles) continue; labels.add(f); } taskCount = DEFAULT_TASK_COUNT + labels.size(); // 1 for the caching of all articles int progress = 0; publishProgress(progress); // Cache articles for all categories Data.getInstance().cacheArticles(false, forceUpdate); publishProgress(++progress); // Refresh articles for all labels for (Feed f : labels) { Data.getInstance().updateArticles(f.id, false, false, false, forceUpdate); publishProgress(++progress); } // This stuff will be done in background without UI-notification, but the progress-calls will be done anyway // to ensure the UI is refreshed properly. Data.getInstance().updateVirtualCategories(); publishProgress(++progress); Data.getInstance().updateCategories(false); publishProgress(++progress); Data.getInstance().updateFeeds(Data.VCAT_ALL, false); publishProgress(taskCount); // Move progress forward to 100% // Silently try to synchronize any ids left in TABLE_MARK: Data.getInstance().synchronizeStatus(); // Silently remove articles which belongs to feeds which do not exist on the server anymore: Data.getInstance().purgeOrphanedArticles(); return null; } } @Override public void itemSelected(MainListFragment source, int selectedIndex, int selectedId) { switch (source.getType()) { case CATEGORY: switch (decideCategorySelection(selectedId)) { case SELECTED_VIRTUAL_CATEGORY: displayHeadlines(selectedId, 0, false); break; case SELECTED_LABEL: displayHeadlines(selectedId, -2, false); break; case SELECTED_CATEGORY: if (Controller.getInstance().invertBrowsing()) { displayHeadlines(FeedHeadlineActivity.FEED_NO_ID, selectedId, true); } else { displayFeed(selectedId); } break; } break; case FEED: FeedListFragment feeds = (FeedListFragment) source; displayHeadlines(selectedId, feeds.getCategoryId(), false); break; default: Toast.makeText(this, "Invalid request!", Toast.LENGTH_SHORT).show(); break; } } public void displayHeadlines(int feedId, int categoryId, boolean selectArticles) { Intent i = new Intent(this, FeedHeadlineActivity.class); i.putExtra(FeedHeadlineListFragment.FEED_CAT_ID, categoryId); i.putExtra(FeedHeadlineListFragment.FEED_ID, feedId); i.putExtra(FeedHeadlineListFragment.FEED_SELECT_ARTICLES, selectArticles); i.putExtra(FeedHeadlineListFragment.ARTICLE_ID, Integer.MIN_VALUE); startActivity(i); } public void displayFeed(int categoryId) { hideFeedFragment(); selectedCategoryId = categoryId; feedFragment = FeedListFragment.newInstance(categoryId); // Clear back stack getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frame_sub, feedFragment, FeedListFragment.FRAGMENT); // Animation if (Controller.isTablet) ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.fade_out, android.R.anim.fade_in, R.anim.slide_out_left); else ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if (!Controller.isTablet) ft.addToBackStack(null); ft.commit(); } public void hideFeedFragment() { if (feedFragment == null) return; FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(feedFragment); ft.commit(); feedFragment = null; } private static int decideCategorySelection(int selectedId) { if (selectedId < 0 && selectedId >= -4) { return SELECTED_VIRTUAL_CATEGORY; } else if (selectedId < -10) { return SELECTED_LABEL; } else { return SELECTED_CATEGORY; } } @Override public void onBackPressed() { selectedCategoryId = Integer.MIN_VALUE; super.onBackPressed(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/CategoryActivity.java
Java
gpl3
13,475
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.fragments.ArticleFragment; import org.ttrssreader.gui.fragments.FeedHeadlineListFragment; import org.ttrssreader.gui.fragments.MainListFragment; import org.ttrssreader.utils.AsyncTask; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class FeedHeadlineActivity extends MenuActivity { protected static final String TAG = FeedHeadlineActivity.class.getSimpleName(); public static final int FEED_NO_ID = 37846914; private int categoryId = Integer.MIN_VALUE; private int feedId = Integer.MIN_VALUE; private boolean selectArticlesForCategory = false; private FeedHeadlineUpdater headlineUpdater = null; private static final String SELECTED = "SELECTED"; private int selectedArticleId = Integer.MIN_VALUE; private FeedHeadlineListFragment headlineFragment; private ArticleFragment articleFragment; @Override protected void onCreate(Bundle instance) { super.onCreate(instance); setContentView(R.layout.main); super.initTabletLayout(); Bundle extras = getIntent().getExtras(); if (instance != null) { categoryId = instance.getInt(FeedHeadlineListFragment.FEED_CAT_ID); feedId = instance.getInt(FeedHeadlineListFragment.FEED_ID); selectArticlesForCategory = instance.getBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES); selectedArticleId = instance.getInt(SELECTED, Integer.MIN_VALUE); } else if (extras != null) { categoryId = extras.getInt(FeedHeadlineListFragment.FEED_CAT_ID); feedId = extras.getInt(FeedHeadlineListFragment.FEED_ID); selectArticlesForCategory = extras.getBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES); selectedArticleId = extras.getInt(SELECTED, Integer.MIN_VALUE); } FragmentManager fm = getFragmentManager(); headlineFragment = (FeedHeadlineListFragment) fm.findFragmentByTag(FeedHeadlineListFragment.FRAGMENT); articleFragment = (ArticleFragment) fm.findFragmentByTag(ArticleFragment.FRAGMENT); if (headlineFragment == null) { headlineFragment = FeedHeadlineListFragment.newInstance(feedId, categoryId, selectArticlesForCategory, selectedArticleId); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.frame_main, headlineFragment, FeedHeadlineListFragment.FRAGMENT); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(FeedHeadlineListFragment.FEED_CAT_ID, categoryId); outState.putInt(FeedHeadlineListFragment.FEED_ID, headlineFragment.getFeedId()); outState.putBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES, selectArticlesForCategory); outState.putInt(SELECTED, selectedArticleId); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle instance) { categoryId = instance.getInt(FeedHeadlineListFragment.FEED_CAT_ID); feedId = instance.getInt(FeedHeadlineListFragment.FEED_ID); selectArticlesForCategory = instance.getBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES); selectedArticleId = instance.getInt(SELECTED, Integer.MIN_VALUE); super.onRestoreInstanceState(instance); } @Override public void dataLoadingFinished() { setTitleAndUnread(); } @Override protected void doRefresh() { super.doRefresh(); headlineFragment.doRefresh(); setTitleAndUnread(); } private void setTitleAndUnread() { // Title and unread information: if (headlineFragment != null) { setTitle(headlineFragment.getTitle()); setUnread(headlineFragment.getUnread()); } } @Override protected void doUpdate(boolean forceUpdate) { // Only update if no headlineUpdater already running if (headlineUpdater != null) { if (headlineUpdater.getStatus().equals(AsyncTask.Status.FINISHED)) { headlineUpdater = null; } else { return; } } if (!isCacherRunning()) { headlineUpdater = new FeedHeadlineUpdater(forceUpdate); headlineUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (selectedArticleId != Integer.MIN_VALUE) { getMenuInflater().inflate(R.menu.article, menu); if (Controller.isTablet) super.onCreateOptionsMenu(menu); } else { super.onCreateOptionsMenu(menu); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.removeItem(R.id.Menu_MarkAllRead); menu.removeItem(R.id.Menu_MarkFeedsRead); return super.onPrepareOptionsMenu(menu); } @Override public final boolean onOptionsItemSelected(final MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case R.id.Menu_Refresh: { doUpdate(true); return true; } default: return false; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_N) { openNextFragment(-1); return true; } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_B) { openNextFragment(1); return true; } } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_N || keyCode == KeyEvent.KEYCODE_B) { return true; } } return super.onKeyUp(keyCode, event); } private void openNextFragment(int direction) { if (selectedArticleId != Integer.MIN_VALUE) { openNextArticle(direction); } else { openNextFeed(direction); } } public void openNextArticle(int direction) { // Open next article FragmentManager fm = getFragmentManager(); articleFragment = (ArticleFragment) fm.findFragmentByTag(ArticleFragment.FRAGMENT); if (articleFragment instanceof ArticleFragment) { selectedArticleId = ((ArticleFragment) articleFragment).openNextArticle(direction); headlineFragment.setSelectedId(selectedArticleId); } } public void openNextFeed(int direction) { // Open next Feed headlineFragment.openNextFeed(direction); feedId = headlineFragment.getFeedId(); FragmentManager fm = getFragmentManager(); articleFragment = (ArticleFragment) fm.findFragmentByTag(ArticleFragment.FRAGMENT); if (articleFragment instanceof ArticleFragment) articleFragment.resetParentInformation(); } /** * Updates all articles from the selected feed. */ public class FeedHeadlineUpdater extends ActivityUpdater { private static final int DEFAULT_TASK_COUNT = 2; public FeedHeadlineUpdater(boolean forceUpdate) { super(forceUpdate); } @Override protected Void doInBackground(Void... params) { taskCount = DEFAULT_TASK_COUNT; int progress = 0; boolean displayUnread = Controller.getInstance().onlyUnread(); publishProgress(++progress); // Move progress forward if (selectArticlesForCategory) { Data.getInstance().updateArticles(categoryId, displayUnread, true, false, forceUpdate); } else { Data.getInstance().updateArticles(headlineFragment.getFeedId(), displayUnread, false, false, forceUpdate); } publishProgress(taskCount); // Move progress forward to 100% return null; } } @Override public void itemSelected(MainListFragment source, int selectedIndex, int selectedId) { switch (source.getType()) { case FEEDHEADLINE: displayArticle(selectedId); break; default: Toast.makeText(this, "Invalid request!", Toast.LENGTH_SHORT).show(); break; } } private void displayArticle(int articleId) { hideArticleFragment(); selectedArticleId = articleId; headlineFragment.setSelectedId(selectedArticleId); // Clear back stack getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); if (articleFragment == null) { articleFragment = ArticleFragment.newInstance(articleId, headlineFragment.getFeedId(), categoryId, selectArticlesForCategory, ArticleFragment.ARTICLE_MOVE_DEFAULT); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frame_sub, articleFragment, ArticleFragment.FRAGMENT); // Animation if (Controller.isTablet) ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.fade_out, android.R.anim.fade_in, R.anim.slide_out_left); else ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if (!Controller.isTablet) ft.addToBackStack(null); ft.commit(); } else { // Reuse existing ArticleFragment articleFragment.openArticle(articleId, headlineFragment.getFeedId(), categoryId, selectArticlesForCategory, ArticleFragment.ARTICLE_MOVE_DEFAULT); } } public void hideArticleFragment() { if (articleFragment == null) return; FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(articleFragment); ft.commit(); articleFragment = null; } @Override public void onBackPressed() { selectedArticleId = Integer.MIN_VALUE; super.onBackPressed(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/gui/FeedHeadlineActivity.java
Java
gpl3
11,896
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.controllers; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.ttrssreader.R; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.pojos.Label; import org.ttrssreader.net.IArticleOmitter; import org.ttrssreader.net.IdUpdatedArticleOmitter; import org.ttrssreader.net.JSONConnector; import org.ttrssreader.net.StopJsonParsingException; import org.ttrssreader.utils.Utils; import android.annotation.SuppressLint; import android.content.Context; import android.net.ConnectivityManager; import android.util.Log; @SuppressLint("UseSparseArrays") public class Data { protected static final String TAG = Data.class.getSimpleName(); /** uncategorized */ public static final int VCAT_UNCAT = 0; /** starred */ public static final int VCAT_STAR = -1; /** published */ public static final int VCAT_PUB = -2; /** fresh */ public static final int VCAT_FRESH = -3; /** all articles */ public static final int VCAT_ALL = -4; /** read articles */ public static final int VCAT_READ = -6; public static final int TIME_CATEGORY = 1; public static final int TIME_FEED = 2; public static final int TIME_FEEDHEADLINE = 3; private static final String VIEW_ALL = "all_articles"; private static final String VIEW_UNREAD = "unread"; private Context context; private long time = 0; private long articlesCached; private Map<Integer, Long> articlesChanged = new HashMap<Integer, Long>(); /** map of category id to last changed time */ private Map<Integer, Long> feedsChanged = new HashMap<Integer, Long>(); private long virtCategoriesChanged = 0; private long categoriesChanged = 0; private ConnectivityManager cm; // Singleton (see http://stackoverflow.com/a/11165926) private Data() { } private static class InstanceHolder { private static final Data instance = new Data(); } public static Data getInstance() { return InstanceHolder.instance; } public synchronized void checkAndInitializeData(final Context context) { this.context = context; if (context != null) cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } // *** ARTICLES ********************************************************************* /** * cache all articles * * @param overrideOffline * do not check connected state * @param overrideDelay * if set to {@code true} enforces the update, * otherwise the time from last update will be * considered */ public void cacheArticles(boolean overrideOffline, boolean overrideDelay) { int limit = 400; if (Controller.getInstance().isLowMemory()) limit = limit / 2; if (!overrideDelay && (time > (System.currentTimeMillis() - Utils.UPDATE_TIME))) { return; } else if (!Utils.isConnected(cm) && !(overrideOffline && Utils.checkConnected(cm))) { return; } Set<Article> articles = new HashSet<Article>(); int sinceId = Controller.getInstance().getSinceId(); IdUpdatedArticleOmitter unreadUpdatedFilter = new IdUpdatedArticleOmitter("isUnread>0", null); Controller .getInstance() .getConnector() .getHeadlines(articles, VCAT_ALL, limit, VIEW_UNREAD, true, 0, null, null, unreadUpdatedFilter.getIdUpdatedMap().isEmpty() ? null : unreadUpdatedFilter); final Article newestCachedArticle = DBHelper.getInstance().getArticle(sinceId); IArticleOmitter updatedFilter = (newestCachedArticle == null) ? null : new IArticleOmitter() { public Date lastUpdated = newestCachedArticle.updated; @Override public boolean omitArticle(Article.ArticleField field, Article a) throws StopJsonParsingException { boolean skip = false; switch (field) { case unread: if (a.isUnread) skip = true; break; case updated: if (a.updated != null && lastUpdated.after(a.updated)) throw new StopJsonParsingException("Stop processing on article ID=" + a.id + " updated on " + lastUpdated); default: break; } return skip; } }; Controller.getInstance().getConnector() .getHeadlines(articles, VCAT_ALL, limit, VIEW_ALL, true, sinceId, null, null, updatedFilter); handleInsertArticles(articles, true); // Only mark as updated if the calls were successful if (!articles.isEmpty() || !unreadUpdatedFilter.getOmittedArticles().isEmpty()) { time = System.currentTimeMillis(); notifyListeners(); // Store all category-ids and ids of all feeds for this category in db articlesCached = time; for (Category c : DBHelper.getInstance().getAllCategories()) { feedsChanged.put(c.id, time); } Set<Integer> articleUnreadIds = new HashSet<Integer>(); for (Article a : articles) { if (a.isUnread) { articleUnreadIds.add(Integer.valueOf(a.id)); } } articleUnreadIds.addAll(unreadUpdatedFilter.getOmittedArticles()); Log.d(TAG, "Amount of unread articles: " + articleUnreadIds.size()); DBHelper.getInstance().markRead(VCAT_ALL, false); DBHelper.getInstance().markArticles(articleUnreadIds, "isUnread", 1); } } /** * update articles for specified feed/category * * @param feedId * feed/category to be updated * @param displayOnlyUnread * flag, that indicates, that only unread * articles should be shown * @param isCat * if set to {@code true}, then {@code feedId} is actually the category ID * @param overrideOffline * should the "work offline" state be ignored? * @param overrideDelay * should the last update time be ignored? */ public void updateArticles(int feedId, boolean displayOnlyUnread, boolean isCat, boolean overrideOffline, boolean overrideDelay) { Long time = articlesChanged.get(feedId); if (isCat) // Category-Ids are in feedsChanged time = feedsChanged.get(feedId); if (time == null) time = Long.valueOf(0); if (articlesCached > time && !(feedId == VCAT_PUB || feedId == VCAT_STAR)) time = articlesCached; if (!overrideDelay && time > System.currentTimeMillis() - Utils.UPDATE_TIME) { return; } else if (!Utils.isConnected(cm) && !(overrideOffline && Utils.checkConnected(cm))) { return; } boolean isVcat = (feedId == VCAT_PUB || feedId == VCAT_STAR); int sinceId = 0; IArticleOmitter filter; if (isVcat) { // Display all articles for Starred/Published: displayOnlyUnread = false; // Don't omit any articles, isPublished should never be < 0: filter = new IdUpdatedArticleOmitter("isPublished<0", null); } else { sinceId = Controller.getInstance().getSinceId(); // TODO: passing null adds all(!) articles to the map, this can take a second or two on slow devices... filter = new IdUpdatedArticleOmitter(null, null); } // Calculate an appropriate upper limit for the number of articles int limit = calculateLimit(feedId, displayOnlyUnread, isCat); if (Controller.getInstance().isLowMemory()) limit = limit / 2; Log.d(TAG, "UPDATE limit: " + limit); Set<Article> articles = new HashSet<Article>(); if (!displayOnlyUnread) { // If not displaying only unread articles: Refresh unread articles to get them too. Controller.getInstance().getConnector() .getHeadlines(articles, feedId, limit, VIEW_UNREAD, isCat, 0, null, null, filter); } String viewMode = (displayOnlyUnread ? VIEW_UNREAD : VIEW_ALL); Controller.getInstance().getConnector() .getHeadlines(articles, feedId, limit, viewMode, isCat, sinceId, null, null, filter); if (isVcat) handlePurgeMarked(articles, feedId); handleInsertArticles(articles, false); long currentTime = System.currentTimeMillis(); // Store requested feed-/category-id and ids of all feeds in db for this category if a category was requested articlesChanged.put(feedId, currentTime); notifyListeners(); if (isCat) { for (Feed f : DBHelper.getInstance().getFeeds(feedId)) { articlesChanged.put(f.id, currentTime); } } } /** * Calculate an appropriate upper limit for the number of articles */ private int calculateLimit(int feedId, boolean displayOnlyUnread, boolean isCat) { int limit = -1; switch (feedId) { case VCAT_STAR: // Starred case VCAT_PUB: // Published limit = JSONConnector.PARAM_LIMIT_MAX_VALUE; break; case VCAT_FRESH: // Fresh limit = DBHelper.getInstance().getUnreadCount(feedId, true); break; case VCAT_ALL: // All Articles limit = DBHelper.getInstance().getUnreadCount(feedId, true); break; default: // Normal categories limit = DBHelper.getInstance().getUnreadCount(feedId, isCat); } if (feedId < -10 && limit <= 0) // Unread-count in DB is wrong for Labels since we only count articles with // feedid = ? limit = 50; return limit; } private void handlePurgeMarked(Set<Article> articles, int feedId) { // TODO Alle Artikel mit ID > minId als nicht starred und nicht published markieren // Search min and max ids int minId = Integer.MAX_VALUE; Set<String> idSet = new HashSet<String>(); for (Article article : articles) { if (article.id < minId) minId = article.id; idSet.add(article.id + ""); } String idList = Utils.separateItems(idSet, ","); String vcat = ""; if (feedId == VCAT_STAR) vcat = "isStarred"; else if (feedId == VCAT_PUB) vcat = "isPublished"; else return; DBHelper.getInstance().handlePurgeMarked(idList, minId, vcat); } /** * prepare the DB and store given articles * * @param articles * articles to be stored * @param isCategory */ private void handleInsertArticles(final Collection<Article> articles, boolean isCaching) { if (!articles.isEmpty()) { // Search min and max ids int minId = Integer.MAX_VALUE; int maxId = Integer.MIN_VALUE; for (Article article : articles) { if (article.id > maxId) maxId = article.id; if (article.id < minId) minId = article.id; } DBHelper.getInstance().purgeLastArticles(articles.size()); DBHelper.getInstance().insertArticles(articles); // correct counters according to real local DB-Data DBHelper.getInstance().calculateCounters(); notifyListeners(); // Only store sinceId when doing a full cache of new articles, else it doesn't work. if (isCaching) { Controller.getInstance().setSinceId(maxId); Controller.getInstance().setLastSync(System.currentTimeMillis()); } } } // *** FEEDS ************************************************************************ /** * update DB (delete/insert) with actual feeds information from server * * @param categoryId * id of category, which feeds should be returned * @param overrideOffline * do not check connected state * * @return actual feeds for given category */ public Set<Feed> updateFeeds(int categoryId, boolean overrideOffline) { Long time = feedsChanged.get(categoryId); if (time == null) time = Long.valueOf(0); if (time > System.currentTimeMillis() - Utils.UPDATE_TIME) { return null; } else if (Utils.isConnected(cm) || (overrideOffline && Utils.checkConnected(cm))) { Set<Feed> ret = new LinkedHashSet<Feed>(); Set<Feed> feeds = Controller.getInstance().getConnector().getFeeds(); // Only delete feeds if we got new feeds... if (!feeds.isEmpty()) { for (Feed f : feeds) { if (categoryId == VCAT_ALL || f.categoryId == categoryId) ret.add(f); feedsChanged.put(f.categoryId, System.currentTimeMillis()); } DBHelper.getInstance().deleteFeeds(); DBHelper.getInstance().insertFeeds(feeds); // Store requested category-id and ids of all received feeds feedsChanged.put(categoryId, System.currentTimeMillis()); notifyListeners(); } return ret; } return null; } // *** CATEGORIES ******************************************************************* public Set<Category> updateVirtualCategories() { if (virtCategoriesChanged > System.currentTimeMillis() - Utils.UPDATE_TIME) return null; String vCatAllArticles = ""; String vCatFreshArticles = ""; String vCatPublishedArticles = ""; String vCatStarredArticles = ""; String uncatFeeds = ""; if (context != null) { vCatAllArticles = (String) context.getText(R.string.VCategory_AllArticles); vCatFreshArticles = (String) context.getText(R.string.VCategory_FreshArticles); vCatPublishedArticles = (String) context.getText(R.string.VCategory_PublishedArticles); vCatStarredArticles = (String) context.getText(R.string.VCategory_StarredArticles); uncatFeeds = (String) context.getText(R.string.Feed_UncategorizedFeeds); } Set<Category> vCats = new LinkedHashSet<Category>(); vCats.add(new Category(VCAT_ALL, vCatAllArticles, DBHelper.getInstance().getUnreadCount(VCAT_ALL, true))); vCats.add(new Category(VCAT_FRESH, vCatFreshArticles, DBHelper.getInstance().getUnreadCount(VCAT_FRESH, true))); vCats.add(new Category(VCAT_PUB, vCatPublishedArticles, DBHelper.getInstance().getUnreadCount(VCAT_PUB, true))); vCats.add(new Category(VCAT_STAR, vCatStarredArticles, DBHelper.getInstance().getUnreadCount(VCAT_STAR, true))); vCats.add(new Category(VCAT_UNCAT, uncatFeeds, DBHelper.getInstance().getUnreadCount(VCAT_UNCAT, true))); DBHelper.getInstance().insertCategories(vCats); notifyListeners(); virtCategoriesChanged = System.currentTimeMillis(); return vCats; } /** * update DB (delete/insert) with actual categories information from server * * @param overrideOffline * do not check connected state * * @return actual categories */ public Set<Category> updateCategories(boolean overrideOffline) { if (categoriesChanged > System.currentTimeMillis() - Utils.UPDATE_TIME) { return null; } else if (Utils.isConnected(cm) || overrideOffline) { Set<Category> categories = Controller.getInstance().getConnector().getCategories(); if (!categories.isEmpty()) { DBHelper.getInstance().deleteCategories(false); DBHelper.getInstance().insertCategories(categories); categoriesChanged = System.currentTimeMillis(); notifyListeners(); } return categories; } return null; } // *** STATUS ******************************************************************* public void setArticleRead(Set<Integer> ids, int articleState) { boolean erg = false; if (Utils.isConnected(cm)) erg = Controller.getInstance().getConnector().setArticleRead(ids, articleState); if (!erg) DBHelper.getInstance().markUnsynchronizedStates(ids, DBHelper.MARK_READ, articleState); } public void setArticleStarred(int articleId, int articleState) { boolean erg = false; Set<Integer> ids = new HashSet<Integer>(); ids.add(articleId); if (Utils.isConnected(cm)) erg = Controller.getInstance().getConnector().setArticleStarred(ids, articleState); if (!erg) DBHelper.getInstance().markUnsynchronizedStates(ids, DBHelper.MARK_STAR, articleState); } public void setArticlePublished(int articleId, int articleState, String note) { boolean erg = false; Map<Integer, String> ids = new HashMap<Integer, String>(); ids.put(articleId, note); if (Utils.isConnected(cm)) erg = Controller.getInstance().getConnector().setArticlePublished(ids, articleState); // Write changes to cache if calling the server failed if (!erg) { DBHelper.getInstance().markUnsynchronizedStates(ids.keySet(), DBHelper.MARK_PUBLISH, articleState); DBHelper.getInstance().markUnsynchronizedNotes(ids, DBHelper.MARK_PUBLISH); } } /** * mark all articles in given category/feed as read * * @param id * category/feed ID * @param isCategory * if set to {@code true}, then given id is category * ID, otherwise - feed ID */ public void setRead(int id, boolean isCategory) { Collection<Integer> markedArticleIds = DBHelper.getInstance().markRead(id, isCategory); if (markedArticleIds != null) { notifyListeners(); boolean isSync = false; if (Utils.isConnected(cm)) { isSync = Controller.getInstance().getConnector().setRead(id, isCategory); } if (!isSync) { DBHelper.getInstance().markUnsynchronizedStates(markedArticleIds, DBHelper.MARK_READ, 0); } } } public boolean shareToPublished(String title, String url, String content) { if (Utils.isConnected(cm)) return Controller.getInstance().getConnector().shareToPublished(title, url, content); return false; } public JSONConnector.SubscriptionResponse feedSubscribe(String feed_url, int category_id) { if (Utils.isConnected(cm)) return Controller.getInstance().getConnector().feedSubscribe(feed_url, category_id); return null; } public boolean feedUnsubscribe(int feed_id) { if (Utils.isConnected(cm)) return Controller.getInstance().getConnector().feedUnsubscribe(feed_id); return false; } public String getPref(String pref) { if (Utils.isConnected(cm)) return Controller.getInstance().getConnector().getPref(pref); return null; } public int getVersion() { if (Utils.isConnected(cm)) return Controller.getInstance().getConnector().getVersion(); return -1; } public Set<Label> getLabels(int articleId) { Set<Label> ret = DBHelper.getInstance().getLabelsForArticle(articleId); return ret; } public boolean setLabel(Integer articleId, Label label) { Set<Integer> set = new HashSet<Integer>(); set.add(articleId); return setLabel(set, label); } public boolean setLabel(Set<Integer> articleIds, Label label) { DBHelper.getInstance().insertLabels(articleIds, label, label.checked); notifyListeners(); boolean erg = false; if (Utils.isConnected(cm)) { Log.d(TAG, "Calling connector with Label: " + label + ") and ids.size() " + articleIds.size()); erg = Controller.getInstance().getConnector().setArticleLabel(articleIds, label.id, label.checked); } return erg; } /** * syncronize read, starred, published articles and notes with server */ public void synchronizeStatus() { if (!Utils.isConnected(cm)) return; long time = System.currentTimeMillis(); String[] marks = new String[] { DBHelper.MARK_READ, DBHelper.MARK_STAR, DBHelper.MARK_PUBLISH, DBHelper.MARK_NOTE }; for (String mark : marks) { Map<Integer, String> idsMark = DBHelper.getInstance().getMarked(mark, 1); Map<Integer, String> idsUnmark = DBHelper.getInstance().getMarked(mark, 0); if (DBHelper.MARK_READ.equals(mark)) { if (Controller.getInstance().getConnector().setArticleRead(idsMark.keySet(), 1)) DBHelper.getInstance().setMarked(idsMark, mark); if (Controller.getInstance().getConnector().setArticleRead(idsUnmark.keySet(), 0)) DBHelper.getInstance().setMarked(idsUnmark, mark); } if (DBHelper.MARK_STAR.equals(mark)) { if (Controller.getInstance().getConnector().setArticleStarred(idsMark.keySet(), 1)) DBHelper.getInstance().setMarked(idsMark, mark); if (Controller.getInstance().getConnector().setArticleStarred(idsUnmark.keySet(), 0)) DBHelper.getInstance().setMarked(idsUnmark, mark); } if (DBHelper.MARK_PUBLISH.equals(mark)) { if (Controller.getInstance().getConnector().setArticlePublished(idsMark, 1)) DBHelper.getInstance().setMarked(idsMark, mark); if (Controller.getInstance().getConnector().setArticlePublished(idsUnmark, 0)) DBHelper.getInstance().setMarked(idsUnmark, mark); } // TODO: Add synchronization of labels } /* * Server doesn't seem to support ID -6 for "read articles" so I'll stick with the already fetched articles. In * the case that we had a cache-run before we can just mark everything as read, then mark all cached articles as * unread and we're done. */ // get read articles from server // articles = new HashSet<Article>(); // int minUnread = DBHelper.getInstance().getMinUnreadId(); // Set<String> skipProperties = new HashSet<String>(Arrays.asList(new String[] { JSONConnector.TITLE, // JSONConnector.UNREAD, JSONConnector.UPDATED, JSONConnector.FEED_ID, JSONConnector.CONTENT, // JSONConnector.URL, JSONConnector.COMMENT_URL, JSONConnector.ATTACHMENTS, JSONConnector.STARRED, // JSONConnector.PUBLISHED })); // // Controller.getInstance().getConnector() // .getHeadlines(articles, VCAT_ALL, 400, VIEW_ALL, true, minUnread, null, skipProperties); Log.d(TAG, String.format("Syncing Status took %sms", (System.currentTimeMillis() - time))); } public void purgeOrphanedArticles() { if (Controller.getInstance().getLastCleanup() > System.currentTimeMillis() - Utils.CLEANUP_TIME) return; DBHelper.getInstance().purgeOrphanedArticles(); Controller.getInstance().setLastCleanup(System.currentTimeMillis()); } private void notifyListeners() { if (!Controller.getInstance().isHeadless()) UpdateController.getInstance().notifyListeners(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/controllers/Data.java
Java
gpl3
25,831
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.controllers; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.ttrssreader.gui.dialogs.ErrorDialog; import org.ttrssreader.imageCache.ImageCache; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.pojos.Label; import org.ttrssreader.model.pojos.RemoteFile; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.os.Build; import android.text.Html; import android.util.Log; import android.widget.Toast; public class DBHelper { protected static final String TAG = DBHelper.class.getSimpleName(); private volatile boolean initialized = false; private static final Object lock = new Object(); public static final String DATABASE_NAME = "ttrss.db"; public static final String DATABASE_BACKUP_NAME = "_backup_"; public static final int DATABASE_VERSION = 60; public static final String TABLE_CATEGORIES = "categories"; public static final String TABLE_FEEDS = "feeds"; public static final String TABLE_ARTICLES = "articles"; public static final String TABLE_ARTICLES2LABELS = "articles2labels"; public static final String TABLE_LABELS = "labels"; public static final String TABLE_MARK = "marked"; public static final String TABLE_REMOTEFILES = "remotefiles"; public static final String TABLE_REMOTEFILE2ARTICLE = "remotefile2article"; public static final String MARK_READ = "isUnread"; public static final String MARK_STAR = "isStarred"; public static final String MARK_PUBLISH = "isPublished"; public static final String MARK_NOTE = "note"; // @formatter:off private static final String CREATE_TABLE_CATEGORIES = "CREATE TABLE " + TABLE_CATEGORIES + " (_id INTEGER PRIMARY KEY," + " title TEXT," + " unread INTEGER)"; private static final String CREATE_TABLE_FEEDS = "CREATE TABLE " + TABLE_FEEDS + " (_id INTEGER PRIMARY KEY," + " categoryId INTEGER," + " title TEXT," + " url TEXT," + " unread INTEGER)"; private static final String CREATE_TABLE_ARTICLES = "CREATE TABLE " + TABLE_ARTICLES + " (_id INTEGER PRIMARY KEY," + " feedId INTEGER," + " title TEXT," + " isUnread INTEGER," + " articleUrl TEXT," + " articleCommentUrl TEXT," + " updateDate INTEGER," + " content TEXT," + " attachments TEXT," + " isStarred INTEGER," + " isPublished INTEGER," + " cachedImages INTEGER DEFAULT 0," + " articleLabels TEXT," + " author TEXT)"; private static final String CREATE_TABLE_ARTICLES2LABELS = "CREATE TABLE " + TABLE_ARTICLES2LABELS + " (articleId INTEGER," + " labelId INTEGER, PRIMARY KEY(articleId, labelId))"; private static final String CREATE_TABLE_MARK = "CREATE TABLE " + TABLE_MARK + " (id INTEGER," + " type INTEGER," + " " + MARK_READ + " INTEGER," + " " + MARK_STAR + " INTEGER," + " " + MARK_PUBLISH + " INTEGER," + " " + MARK_NOTE + " TEXT," + " PRIMARY KEY(id, type))"; private static final String INSERT_CATEGORY = "REPLACE INTO " + TABLE_CATEGORIES + " (_id, title, unread)" + " VALUES (?, ?, ?)"; private static final String INSERT_FEED = "REPLACE INTO " + TABLE_FEEDS + " (_id, categoryId, title, url, unread)" + " VALUES (?, ?, ?, ?, ?)"; private static final String INSERT_ARTICLE = "INSERT OR REPLACE INTO " + TABLE_ARTICLES + " (_id, feedId, title, isUnread, articleUrl, articleCommentUrl, updateDate, content, attachments, isStarred, isPublished, cachedImages, articleLabels, author)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, coalesce((SELECT cachedImages FROM " + TABLE_ARTICLES + " WHERE _id=?), NULL), ?, ?)"; // This should insert new values or replace existing values but should always keep an already inserted value for "cachedImages". // When inserting it is set to the default value which is 0 (not "NULL"). private static final String INSERT_LABEL = "REPLACE INTO " + TABLE_ARTICLES2LABELS + " (articleId, labelId)" + " VALUES (?, ?)"; private static final String INSERT_REMOTEFILE = "INSERT OR FAIL INTO " + TABLE_REMOTEFILES + " (url, ext)" + " VALUES (?, ?)"; private static final String INSERT_REMOTEFILE2ARTICLE = "INSERT OR IGNORE INTO " + TABLE_REMOTEFILE2ARTICLE + " (remotefileId, articleId)" + " VALUES (?, ?)"; // @formatter:on private Context context; private SQLiteDatabase db; private SQLiteStatement insertCategory; private SQLiteStatement insertFeed; private SQLiteStatement insertArticle; private SQLiteStatement insertLabel; private SQLiteStatement insertRemoteFile; private SQLiteStatement insertRemoteFile2Article; private static boolean specialUpgradeSuccessful = false; // Singleton (see http://stackoverflow.com/a/11165926) private DBHelper() { } private static class InstanceHolder { private static final DBHelper instance = new DBHelper(); } public static DBHelper getInstance() { return InstanceHolder.instance; } public void checkAndInitializeDB(final Context context) { synchronized (lock) { this.context = context; // Check if deleteDB is scheduled or if DeleteOnStartup is set if (Controller.getInstance().isDeleteDBScheduled()) { if (deleteDB()) { Controller.getInstance().setDeleteDBScheduled(false); initializeDBHelper(); return; // Don't need to check if DB is corrupted, it is NEW! } } // Initialize DB if (!initialized) { initializeDBHelper(); } else if (db == null || !db.isOpen()) { initializeDBHelper(); } else { return; // DB was already initialized, no need to check anything. } // Test if DB is accessible, backup and delete if not if (initialized) { Cursor c = null; try { // Try to access the DB c = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_CATEGORIES, null); c.getCount(); if (c.moveToFirst()) c.getInt(0); } catch (Exception e) { Log.e(TAG, "Database was corrupted, creating a new one...", e); closeDB(); File dbFile = context.getDatabasePath(DATABASE_NAME); if (dbFile.delete()) initializeDBHelper(); ErrorDialog .getInstance( context, "The Database was corrupted and had to be recreated. If this happened more than once to you please let me know under what circumstances this happened."); } finally { if (c != null && !c.isClosed()) c.close(); } } } } @SuppressWarnings("deprecation") private boolean initializeDBHelper() { synchronized (lock) { if (context == null) { Log.e(TAG, "Can't handle internal DB without Context-Object."); return false; } if (db != null) closeDB(); OpenHelper openHelper = new OpenHelper(context); db = openHelper.getWritableDatabase(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) db.setLockingEnabled(true); if (specialUpgradeSuccessful) { // Re-open DB for final usage: db.close(); openHelper = new OpenHelper(context); db = openHelper.getWritableDatabase(); Toast.makeText(context, "ImageCache is beeing cleaned...", Toast.LENGTH_LONG).show(); new org.ttrssreader.utils.AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... params) { // Clear ImageCache since no files are in REMOTE_FILES anymore and we dont want to leave them // there forever: ImageCache imageCache = Controller.getInstance().getImageCache(); imageCache.fillMemoryCacheFromDisk(); File cacheFolder = new File(imageCache.getDiskCacheDirectory()); if (cacheFolder.isDirectory()) { try { FileUtils.deleteDirectory(cacheFolder); } catch (IOException e) { e.printStackTrace(); } } return null; }; protected void onPostExecute(Void result) { Toast.makeText(context, "ImageCache has been cleaned up...", Toast.LENGTH_LONG).show(); }; }.execute(); } insertCategory = db.compileStatement(INSERT_CATEGORY); insertFeed = db.compileStatement(INSERT_FEED); insertArticle = db.compileStatement(INSERT_ARTICLE); insertLabel = db.compileStatement(INSERT_LABEL); insertRemoteFile = db.compileStatement(INSERT_REMOTEFILE); insertRemoteFile2Article = db.compileStatement(INSERT_REMOTEFILE2ARTICLE); db.acquireReference(); initialized = true; return true; } } private boolean deleteDB() { synchronized (lock) { if (context == null) return false; Log.i(TAG, "Deleting Database as requested by preferences."); File f = context.getDatabasePath(DATABASE_NAME); if (f.exists()) { if (db != null) { closeDB(); } return f.delete(); } return false; } } private void closeDB() { synchronized (lock) { db.releaseReference(); db.close(); db = null; } } private boolean isDBAvailable() { synchronized (lock) { if (db != null && db.isOpen()) return true; if (db != null) { OpenHelper openHelper = new OpenHelper(context); db = openHelper.getWritableDatabase(); initialized = db.isOpen(); return initialized; } else { Log.i(TAG, "Controller not initialized, trying to do that now..."); initializeDBHelper(); return true; } } } private static class OpenHelper extends SQLiteOpenHelper { OpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * set wished DB modes on DB * * @param db * DB to be used */ @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); if (!db.isReadOnly()) { // Enable foreign key constraints db.execSQL("PRAGMA foreign_keys=ON;"); } } /** * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase) */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_CATEGORIES); db.execSQL(CREATE_TABLE_FEEDS); db.execSQL(CREATE_TABLE_ARTICLES); db.execSQL(CREATE_TABLE_ARTICLES2LABELS); db.execSQL(CREATE_TABLE_MARK); createRemoteFilesSupportDBObjects(db); } /** * upgrade the DB * * @param db * The database. * @param oldVersion * The old database version. * @param newVersion * The new database version. * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int) */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { boolean didUpgrade = false; if (oldVersion < 40) { String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN isStarred INTEGER"; Log.i(TAG, String.format("Upgrading database from %s to 40.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 42) { String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN isPublished INTEGER"; Log.i(TAG, String.format("Upgrading database from %s to 42.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 45) { // @formatter:off String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_MARK + " (id INTEGER," + " type INTEGER," + " " + MARK_READ + " INTEGER," + " " + MARK_STAR + " INTEGER," + " " + MARK_PUBLISH + " INTEGER," + " PRIMARY KEY(id, type))"; // @formatter:on Log.i(TAG, String.format("Upgrading database from %s to 45.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 46) { // @formatter:off String sql = "DROP TABLE IF EXISTS " + TABLE_MARK; String sql2 = "CREATE TABLE IF NOT EXISTS " + TABLE_MARK + " (id INTEGER PRIMARY KEY," + " " + MARK_READ + " INTEGER," + " " + MARK_STAR + " INTEGER," + " " + MARK_PUBLISH + " INTEGER)"; // @formatter:on Log.i(TAG, String.format("Upgrading database from %s to 46.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); Log.i(TAG, String.format(" (Executing: %s", sql2)); db.execSQL(sql); db.execSQL(sql2); didUpgrade = true; } if (oldVersion < 47) { String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN cachedImages INTEGER DEFAULT 0"; Log.i(TAG, String.format("Upgrading database from %s to 47.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 48) { // @formatter:off String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_MARK + " (id INTEGER," + " type INTEGER," + " " + MARK_READ + " INTEGER," + " " + MARK_STAR + " INTEGER," + " " + MARK_PUBLISH + " INTEGER," + " PRIMARY KEY(id, type))"; // @formatter:on Log.i(TAG, String.format("Upgrading database from %s to 48.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 49) { // @formatter:off String sql = "CREATE TABLE " + TABLE_ARTICLES2LABELS + " (articleId INTEGER," + " labelId INTEGER, PRIMARY KEY(articleId, labelId))"; // @formatter:on Log.i(TAG, String.format("Upgrading database from %s to 49.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 50) { Log.i(TAG, String.format("Upgrading database from %s to 50.", oldVersion)); ContentValues cv = new ContentValues(1); cv.put("cachedImages", 0); db.update(TABLE_ARTICLES, cv, "cachedImages IS null", null); didUpgrade = true; } if (oldVersion < 51) { // @formatter:off String sql = "DROP TABLE IF EXISTS " + TABLE_MARK; String sql2 = "CREATE TABLE " + TABLE_MARK + " (id INTEGER," + " type INTEGER," + " " + MARK_READ + " INTEGER," + " " + MARK_STAR + " INTEGER," + " " + MARK_PUBLISH + " INTEGER," + " " + MARK_NOTE + " TEXT," + " PRIMARY KEY(id, type))"; // @formatter:on Log.i(TAG, String.format("Upgrading database from %s to 51.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); Log.i(TAG, String.format(" (Executing: %s", sql2)); db.execSQL(sql); db.execSQL(sql2); didUpgrade = true; } if (oldVersion < 52) { // @formatter:off String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN articleLabels TEXT"; // @formatter:on Log.i(TAG, String.format("Upgrading database from %s to 52.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 53) { Log.i(TAG, String.format("Upgrading database from %s to 53.", oldVersion)); didUpgrade = createRemoteFilesSupportDBObjects(db); if (didUpgrade) { ContentValues cv = new ContentValues(1); cv.putNull("cachedImages"); db.update(TABLE_ARTICLES, cv, null, null); ImageCache ic = Controller.getInstance().getImageCache(); if (ic != null) { ic.clear(); } } } if (oldVersion < 58) { Log.i(TAG, String.format("Upgrading database from %s to 58.", oldVersion)); // Rename columns "id" to "_id" by modifying the table structure: db.beginTransaction(); try { db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMOTEFILES); db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMOTEFILE2ARTICLE); db.execSQL("PRAGMA writable_schema=1;"); String sql = "UPDATE SQLITE_MASTER SET SQL = '%s' WHERE NAME = '%s';"; db.execSQL(String.format(sql, CREATE_TABLE_CATEGORIES, TABLE_CATEGORIES)); db.execSQL(String.format(sql, CREATE_TABLE_FEEDS, TABLE_FEEDS)); db.execSQL(String.format(sql, CREATE_TABLE_ARTICLES, TABLE_ARTICLES)); db.execSQL("PRAGMA writable_schema=0;"); if (createRemoteFilesSupportDBObjects(db)) { db.setTransactionSuccessful(); didUpgrade = true; } } finally { db.execSQL("PRAGMA foreign_keys=ON;"); db.endTransaction(); specialUpgradeSuccessful = true; } } if (oldVersion < 59) { // @formatter:off String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN author TEXT"; // @formatter:on Log.i(TAG, String.format("Upgrading database from %s to 59.", oldVersion)); Log.i(TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 60) { Log.i(TAG, String.format("Upgrading database from %s to 59.", oldVersion)); Log.i(TAG, String.format(" (Re-Creating View: remotefiles_sequence )")); createRemotefilesView(db); didUpgrade = true; } if (didUpgrade == false) { Log.i(TAG, "Upgrading database, this will drop tables and recreate."); db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIES); db.execSQL("DROP TABLE IF EXISTS " + TABLE_FEEDS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_ARTICLES); db.execSQL("DROP TABLE IF EXISTS " + TABLE_MARK); db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMOTEFILES); onCreate(db); } } /** * create DB objects (tables, triggers, views) which * are necessary for file cache support * * @param db * current database */ private boolean createRemoteFilesSupportDBObjects(SQLiteDatabase db) { boolean success = false; try { createRemotefiles(db); createRemotefiles2Articles(db); createRemotefilesView(db); success = true; } catch (SQLException e) { Log.e(TAG, "Creation of remote file support DB objects failed.\n" + e); } return success; } private void createRemotefiles(SQLiteDatabase db) { // @formatter:off // remote files (images, attachments, etc) belonging to articles, // which are locally stored (cached) db.execSQL("CREATE TABLE " + TABLE_REMOTEFILES + " (id INTEGER PRIMARY KEY AUTOINCREMENT," // remote file URL + " url TEXT UNIQUE NOT NULL," // file size + " length INTEGER DEFAULT 0," // extension - some kind of additional info // (i.e. file extension) + " ext TEXT NOT NULL," // unix timestamp of last change // (set automatically by triggers) + " updateDate INTEGER," // boolean flag determining if the file is locally stored + " cached INTEGER DEFAULT 0)"); // index for quiicker search by by URL db.execSQL("DROP INDEX IF EXISTS idx_remotefiles_by_url"); db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS idx_remotefiles_by_url" + " ON " + TABLE_REMOTEFILES + " (url)"); // sets last change unix timestamp after row creation db.execSQL("DROP TRIGGER IF EXISTS insert_remotefiles"); db.execSQL("CREATE TRIGGER IF NOT EXISTS insert_remotefiles AFTER INSERT" + " ON " + TABLE_REMOTEFILES + " BEGIN" + " UPDATE " + TABLE_REMOTEFILES + " SET updateDate = strftime('%s', 'now')" + " WHERE id = new.id;" + " END"); // sets last change unix timestamp after row update db.execSQL("DROP TRIGGER IF EXISTS update_remotefiles_lastchanged"); db.execSQL("CREATE TRIGGER IF NOT EXISTS update_remotefiles_lastchanged AFTER UPDATE" + " ON " + TABLE_REMOTEFILES + " BEGIN" + " UPDATE " + TABLE_REMOTEFILES + " SET updateDate = strftime('%s', 'now')" + " WHERE id = new.id;" + " END"); // @formatter:on } private void createRemotefiles2Articles(SQLiteDatabase db) { // @formatter:off // m to n relations between articles and remote files db.execSQL("CREATE TABLE " + TABLE_REMOTEFILE2ARTICLE // ID of remote file + "(remotefileId INTEGER" + " REFERENCES " + TABLE_REMOTEFILES + "(id)" + " ON DELETE CASCADE," // ID of article + " articleId INTEGER" + " REFERENCES " + TABLE_ARTICLES + "(_id)" + " ON UPDATE CASCADE" + " ON DELETE NO ACTION," // if both IDs are known, then the row should be found faster + " PRIMARY KEY(remotefileId, articleId))"); // update count of cached images for article on change of "cached" // field of remotefiles db.execSQL("DROP TRIGGER IF EXISTS update_remotefiles_articlefiles"); db.execSQL("CREATE TRIGGER IF NOT EXISTS update_remotefiles_articlefiles AFTER UPDATE" + " OF cached" + " ON " + TABLE_REMOTEFILES + " BEGIN" + " UPDATE " + TABLE_ARTICLES + "" + " SET" + " cachedImages = (" + " SELECT" + " COUNT(r.id)" + " FROM " + TABLE_REMOTEFILES + " r," + TABLE_REMOTEFILE2ARTICLE + " m" + " WHERE" + " m.remotefileId=r.id" + " AND m.articleId=" + TABLE_ARTICLES + "._id" + " AND r.cached=1)" + " WHERE _id IN (" + " SELECT" + " a._id" + " FROM " + TABLE_REMOTEFILE2ARTICLE + " m," + TABLE_ARTICLES + " a" + " WHERE" + " m.remotefileId=new.id AND m.articleId=a._id);" + " END"); // @formatter:on } private void createRemotefilesView(SQLiteDatabase db) { // @formatter:off // represents importance of cached files // the sequence is defined by // 1. the article to which the remote file belongs to is not read // 2. update date of the article to which the remote file belongs to // 3. the file length db.execSQL("DROP VIEW IF EXISTS remotefile_sequence"); db.execSQL("CREATE VIEW IF NOT EXISTS remotefile_sequence AS" + " SELECT r.*, MAX(a.isUnread) AS isUnread," + " MAX(a.updateDate) AS articleUpdateDate," + " MAX(a.isUnread)||MAX(a.updateDate)||(100000000000-r.length)" + " AS ord" + " FROM " + TABLE_REMOTEFILES + " r," + TABLE_REMOTEFILE2ARTICLE + " m," + TABLE_ARTICLES + " a" + " WHERE m.remotefileId=r.id AND m.articleId=a._id" + " GROUP BY r.id"); // @formatter:on } } /** * Used by SubscribeActivity to directly access the DB and get a cursor for the List of Categories.<br> * PLEASE NOTE: Don't forget to close the received cursor! * * @see android.database.sqlite.SQLiteDatabase#rawQuery(String, String[]) */ @Deprecated public Cursor query(String sql, String[] selectionArgs) { if (!isDBAvailable()) return null; Cursor cursor = db.rawQuery(sql, selectionArgs); return cursor; } // *******| INSERT |******************************************************************* private void insertCategory(int id, String title, int unread) { if (title == null) title = ""; synchronized (insertCategory) { insertCategory.bindLong(1, id); insertCategory.bindString(2, title); insertCategory.bindLong(3, unread); if (!isDBAvailable()) return; insertCategory.execute(); } } public void insertCategories(Set<Category> set) { if (!isDBAvailable() || set == null) return; db.beginTransaction(); try { for (Category c : set) { insertCategory(c.id, c.title, c.unread); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } private void insertFeed(int id, int categoryId, String title, String url, int unread) { if (title == null) title = ""; if (url == null) url = ""; synchronized (insertFeed) { insertFeed.bindLong(1, Integer.valueOf(id).longValue()); insertFeed.bindLong(2, Integer.valueOf(categoryId).longValue()); insertFeed.bindString(3, title); insertFeed.bindString(4, url); insertFeed.bindLong(5, unread); if (!isDBAvailable()) return; insertFeed.execute(); } } public void insertFeeds(Set<Feed> set) { if (!isDBAvailable() || set == null) return; db.beginTransaction(); try { for (Feed f : set) { insertFeed(f.id, f.categoryId, f.title, f.url, f.unread); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } private void insertArticleIntern(Article a) { if (a.title == null) a.title = ""; if (a.content == null) a.content = ""; if (a.url == null) a.url = ""; if (a.commentUrl == null) a.commentUrl = ""; if (a.updated == null) a.updated = new Date(); if (a.attachments == null) a.attachments = new LinkedHashSet<String>(); if (a.labels == null) a.labels = new LinkedHashSet<Label>(); if (a.author == null) a.author = ""; // articleLabels long retId = -1; synchronized (insertArticle) { insertArticle.bindLong(1, a.id); insertArticle.bindLong(2, a.feedId); insertArticle.bindString(3, Html.fromHtml(a.title).toString()); insertArticle.bindLong(4, (a.isUnread ? 1 : 0)); insertArticle.bindString(5, a.url); insertArticle.bindString(6, a.commentUrl); insertArticle.bindLong(7, a.updated.getTime()); insertArticle.bindString(8, a.content); insertArticle.bindString(9, Utils.separateItems(a.attachments, ";")); insertArticle.bindLong(10, (a.isStarred ? 1 : 0)); insertArticle.bindLong(11, (a.isPublished ? 1 : 0)); insertArticle.bindLong(12, a.id); // ID again for the where-clause insertArticle.bindString(13, Utils.separateItems(a.labels, "---")); insertArticle.bindString(14, a.author); if (!isDBAvailable()) return; retId = insertArticle.executeInsert(); } if (retId != -1) insertLabels(a.id, a.labels); } public void insertArticle(Article a) { if (isDBAvailable()) insertArticleIntern(a); } public void insertArticles(Collection<Article> articles) { if (!isDBAvailable() || articles == null || articles.isEmpty()) return; db.beginTransaction(); try { for (Article a : articles) { insertArticleIntern(a); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } private void insertLabels(int articleId, Set<Label> labels) { for (Label label : labels) { insertLabel(articleId, label); } } private void insertLabel(int articleId, Label label) { if (label.id < -10) { if (!isDBAvailable()) return; synchronized (insertLabel) { insertLabel.bindLong(1, articleId); insertLabel.bindLong(2, label.id); insertLabel.executeInsert(); } } } public void removeLabel(int articleId, Label label) { if (label.id < -10) { String[] args = new String[] { articleId + "", label.id + "" }; if (!isDBAvailable()) return; db.delete(TABLE_ARTICLES2LABELS, "articleId=? AND labelId=?", args); } } public void insertLabels(Set<Integer> articleIds, Label label, boolean assign) { if (!isDBAvailable()) return; for (Integer articleId : articleIds) { if (assign) insertLabel(articleId, label); else removeLabel(articleId, label); } } /** * insert given remote file into DB * * @param url * remote file URL * @return remote file id, which was inserted or already exist in DB */ private long insertRemoteFile(String url) { long ret = 0; try { synchronized (insertRemoteFile) { insertRemoteFile.bindString(1, url); // extension (reserved for future) insertRemoteFile.bindString(2, ""); if (isDBAvailable()) ret = insertRemoteFile.executeInsert(); } } catch (SQLException e) { // if this remote file already in DB, get its ID ret = getRemoteFile(url).id; } return ret; } /** * insert given relation (remotefileId <-> articleId) into DB * * @param rfId * remote file ID * @param aId * article ID */ private void insertRemoteFile2Article(long rfId, long aId) { synchronized (insertRemoteFile2Article) { insertRemoteFile2Article.bindLong(1, rfId); // extension (reserved for future) insertRemoteFile2Article.bindLong(2, aId); if (isDBAvailable()) insertRemoteFile2Article.executeInsert(); } } // *******| UPDATE |******************************************************************* /** * set read status in DB for given category/feed * * @param id * category/feed ID * @param isCategory * if set to {@code true}, then given id is category * ID, otherwise - feed ID * * @return collection of article IDs, which was marked as read or {@code null} if nothing was changed */ public Collection<Integer> markRead(int id, boolean isCategory) { Set<Integer> markedIds = null; if (isDBAvailable()) { StringBuilder where = new StringBuilder(); StringBuilder feedIds = new StringBuilder(); switch (id) { case Data.VCAT_ALL: where.append(" 1 "); // Select everything... break; case Data.VCAT_FRESH: long time = System.currentTimeMillis() - Controller.getInstance().getFreshArticleMaxAge(); where.append(" updateDate > ").append(time); break; case Data.VCAT_PUB: where.append(" isPublished > 0 "); break; case Data.VCAT_STAR: where.append(" isStarred > 0 "); break; default: if (isCategory) { feedIds.append("SELECT _id FROM ").append(TABLE_FEEDS).append(" WHERE categoryId=").append(id); } else { feedIds.append(id); } where.append(" feedId IN (").append(feedIds).append(") "); break; } where.append(" and isUnread>0 "); Cursor c = null; db.beginTransaction(); try { // select id from articles where categoryId in (...) c = db.query(TABLE_ARTICLES, new String[] { "_id" }, where.toString(), null, null, null, null); int count = c.getCount(); if (count > 0) { markedIds = new HashSet<Integer>(count); while (c.moveToNext()) { markedIds.add(c.getInt(0)); } } db.setTransactionSuccessful(); } finally { if (c != null && !c.isClosed()) c.close(); db.endTransaction(); } } if (markedIds != null && !markedIds.isEmpty()) { markArticles(markedIds, "isUnread", 0); } return markedIds; } public void markLabelRead(int labelId) { ContentValues cv = new ContentValues(1); cv.put("isUnread", 0); String idList = "SELECT _id id FROM " + TABLE_ARTICLES + " AS a, " + TABLE_ARTICLES2LABELS + " as l WHERE a._id=l.articleId AND l.labelId=" + labelId; if (!isDBAvailable()) return; db.update(TABLE_ARTICLES, cv, "isUnread>0 AND _id IN(" + idList + ")", null); } /** * mark given property of given articles with given state * * @param idList * set of article IDs, which should be processed * @param mark * mark to be set * @param state * value for the mark */ public void markArticles(Set<Integer> idList, String mark, int state) { if (isDBAvailable() && idList != null && !idList.isEmpty()) { db.beginTransaction(); try { for (String ids : StringSupport.convertListToString(idList, 400)) { markArticles(ids, mark, state); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } calculateCounters(); } } /** * mark given property of given article with given state * * @param id * set of article IDs, which should be processed * @param mark * mark to be set * @param state * value for the mark */ public void markArticle(int id, String mark, int state) { if (!isDBAvailable()) return; db.beginTransaction(); try { markArticles("" + id, mark, state); calculateCounters(); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } /** * mark given property of given articles with given state * * @param idList * set of article IDs, which should be processed * @param mark * mark to be set * @param state * value for the mark * @return the number of rows affected */ public int markArticles(String idList, String mark, int state) { int rowCount = 0; if (isDBAvailable()) { ContentValues cv = new ContentValues(1); cv.put(mark, state); rowCount = db.update(TABLE_ARTICLES, cv, "_id IN (" + idList + ") AND ? != ?", new String[] { mark, String.valueOf(state) }); } return rowCount; } public void markUnsynchronizedStates(Collection<Integer> ids, String mark, int state) { // Disabled until further testing and proper SQL has been built. Tries to do the UPDATE and INSERT without // looping over the ids but instead with a list of ids: // Set<String> idList = StringSupport.convertListToString(ids); // for (String s : idList) { // db.execSQL(String.format("UPDATE %s SET %s=%s WHERE id in %s", TABLE_MARK, mark, state, s)); // db.execSQL(String.format("INSERT OR IGNORE INTO %s (id, %s) VALUES (%s, %s)", TABLE_MARK, mark, id, state)); // <- WRONG! // } if (!isDBAvailable()) return; db.beginTransaction(); try { for (Integer id : ids) { // First update, then insert. If row exists it gets updated and second call ignores it, else the second // call inserts it. db.execSQL(String.format("UPDATE %s SET %s=%s WHERE id=%s", TABLE_MARK, mark, state, id)); db.execSQL(String.format("INSERT OR IGNORE INTO %s (id, %s) VALUES (%s, %s)", TABLE_MARK, mark, id, state)); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } // Special treatment for notes since the method markUnsynchronizedStates(...) doesn't support inserting any // additional data. public void markUnsynchronizedNotes(Map<Integer, String> ids, String markPublish) { if (!isDBAvailable()) return; db.beginTransaction(); try { for (Integer id : ids.keySet()) { String note = ids.get(id); if (note == null || note.equals("")) continue; ContentValues cv = new ContentValues(1); cv.put(MARK_NOTE, note); db.update(TABLE_MARK, cv, "id=" + id, null); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } /** * set unread counters for feeds and categories according to real amount * of unread articles * * @return {@code true} if counters was successfully updated, {@code false} otherwise */ public void calculateCounters() { long time = System.currentTimeMillis(); int total = 0; Cursor c = null; ContentValues cv = null; if (!isDBAvailable()) return; db.beginTransaction(); try { cv = new ContentValues(1); cv.put("unread", 0); db.update(TABLE_FEEDS, cv, null, null); db.update(TABLE_CATEGORIES, cv, null, null); try { // select feedId, count(*) from articles where isUnread>0 group by feedId c = db.query(TABLE_ARTICLES, new String[] { "feedId", "count(*)" }, "isUnread>0", null, "feedId", null, null, null); // update feeds while (c.moveToNext()) { int feedId = c.getInt(0); int unreadCount = c.getInt(1); total += unreadCount; cv.put("unread", unreadCount); db.update(TABLE_FEEDS, cv, "_id=" + feedId, null); } } finally { if (c != null && !c.isClosed()) c.close(); } try { // select categoryId, sum(unread) from feeds where categoryId >= 0 group by categoryId c = db.query(TABLE_FEEDS, new String[] { "categoryId", "sum(unread)" }, "categoryId>=0", null, "categoryId", null, null, null); // update real categories while (c.moveToNext()) { int categoryId = c.getInt(0); int unreadCount = c.getInt(1); cv.put("unread", unreadCount); db.update(TABLE_CATEGORIES, cv, "_id=" + categoryId, null); } } finally { if (c != null && !c.isClosed()) c.close(); } cv.put("unread", total); db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_ALL, null); cv.put("unread", getUnreadCount(Data.VCAT_FRESH, true)); db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_FRESH, null); cv.put("unread", getUnreadCount(Data.VCAT_PUB, true)); db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_PUB, null); cv.put("unread", getUnreadCount(Data.VCAT_STAR, true)); db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_STAR, null); db.setTransactionSuccessful(); } finally { db.endTransaction(); } Log.i(TAG, String.format("Fixed counters, total unread: %s (took %sms)", total, (System.currentTimeMillis() - time))); } /** * update amount of remote file references for article. * normally should only be used with {@code null} ("unknown") and {@code 0} (no references) * * @param id * ID of article, which should be updated * @param filesCount * new value for remote file references (may be {@code null}) */ public void updateArticleCachedImages(int id, Integer filesCount) { if (isDBAvailable()) { ContentValues cv = new ContentValues(1); if (filesCount == null) { cv.putNull("cachedImages"); } else { cv.put("cachedImages", filesCount); } db.update(TABLE_ARTICLES, cv, "_id=?", new String[] { String.valueOf(id) }); } } public void deleteCategories(boolean withVirtualCategories) { String wherePart = ""; if (!withVirtualCategories) wherePart = "_id > 0"; if (!isDBAvailable()) return; db.delete(TABLE_CATEGORIES, wherePart, null); } /** * delete all rows from feeds table */ public void deleteFeeds() { if (!isDBAvailable()) return; db.delete(TABLE_FEEDS, null, null); } /** * delete articles and all its resources (e.g. remote files, labels etc.) * * @param whereClause * the optional WHERE clause to apply when deleting. * Passing null will delete all rows. * @param whereArgs * You may include ?s in the where clause, which * will be replaced by the values from whereArgs. The values * will be bound as Strings. * * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ public int safelyDeleteArticles(String whereClause, String[] whereArgs) { int deletedCount = 0; Collection<RemoteFile> rfs = getRemoteFilesForArticles(whereClause, whereArgs, true); if (!rfs.isEmpty()) { Set<Integer> rfIds = new HashSet<Integer>(rfs.size()); for (RemoteFile rf : rfs) { rfIds.add(rf.id); Controller.getInstance().getImageCache().getCacheFile(rf.url).delete(); } deleteRemoteFiles(rfIds); } StringBuilder query = new StringBuilder(); // @formatter:off query.append ( " articleId IN (" ).append( " SELECT _id" ).append( " FROM " ).append( TABLE_ARTICLES ).append( " WHERE " ).append( whereClause ).append( " )" ); // @formatter:on db.beginTransaction(); try { // first, delete article referencies from linking table to preserve foreign key constraint on the next step db.delete(TABLE_REMOTEFILE2ARTICLE, query.toString(), whereArgs); deletedCount = db.delete(TABLE_ARTICLES, whereClause, whereArgs); // TODO Foreign-key constraint failed from // purgeOrphanedArticles() and // safelyDeleteArticles() purgeLabels(); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return deletedCount; } /** * Delete given amount of last updated articles from DB. Published and Starred articles are ignored * so the configured limit is not an exact upper limit to the number of articles in the database. * * @param amountToPurge * amount of articles to be purged */ public void purgeLastArticles(int amountToPurge) { long time = System.currentTimeMillis(); if (isDBAvailable()) { String query = "_id IN ( SELECT _id FROM " + TABLE_ARTICLES + " WHERE isPublished=0 AND isStarred=0 ORDER BY updateDate DESC LIMIT -1 OFFSET " + (Utils.ARTICLE_LIMIT - amountToPurge + ")"); safelyDeleteArticles(query, null); } Log.d(TAG, "purgeLastArticles took " + (System.currentTimeMillis() - time) + "ms"); } /** * delete articles, which belongs to non-existent feeds */ public void purgeOrphanedArticles() { long time = System.currentTimeMillis(); if (isDBAvailable()) { safelyDeleteArticles("feedId NOT IN (SELECT _id FROM " + TABLE_FEEDS + ")", null); } Log.d(TAG, "purgeOrphanedArticles took " + (System.currentTimeMillis() - time) + "ms"); } private void purgeLabels() { if (isDBAvailable()) { // @formatter:off String idsArticles = "SELECT a2l.articleId FROM " + TABLE_ARTICLES2LABELS + " AS a2l LEFT OUTER JOIN " + TABLE_ARTICLES + " AS a" + " ON a2l.articleId = a._id WHERE a._id IS null"; String idsFeeds = "SELECT a2l.labelId FROM " + TABLE_ARTICLES2LABELS + " AS a2l LEFT OUTER JOIN " + TABLE_FEEDS + " AS f" + " ON a2l.labelId = f._id WHERE f._id IS null"; // @formatter:on db.delete(TABLE_ARTICLES2LABELS, "articleId IN(" + idsArticles + ")", null); db.delete(TABLE_ARTICLES2LABELS, "labelId IN(" + idsFeeds + ")", null); } } public void handlePurgeMarked(String idList, int minId, String vcat) { if (isDBAvailable()) { long time = System.currentTimeMillis(); ContentValues cv = new ContentValues(1); cv.put(vcat, 0); int count = db.update(TABLE_ARTICLES, cv, vcat + ">0 AND _id>" + minId + " AND _id NOT IN (" + idList + ")", null); Log.d(TAG, "Marked " + count + " articles " + vcat + "=0 (" + (System.currentTimeMillis() - time) + "ms)"); } } // *******| SELECT |******************************************************************* /** * get minimal ID of unread article, stored in DB * * @return minimal ID of unread article */ public int getMinUnreadId() { int ret = 0; Cursor c = null; try { if (!isDBAvailable()) return ret; c = db.query(TABLE_ARTICLES, new String[] { "min(_id)" }, "isUnread>0", null, null, null, null, null); if (c.moveToFirst()) ret = c.getInt(0); else return 0; } finally { if (c != null && !c.isClosed()) c.close(); } return ret; } /** * get amount of articles stored in the DB * * @return amount of articles stored in the DB */ public int countArticles() { int ret = -1; Cursor c = null; try { if (!isDBAvailable()) return ret; c = db.query(TABLE_ARTICLES, new String[] { "count(*)" }, null, null, null, null, null, null); if (c.moveToFirst()) ret = c.getInt(0); } finally { if (c != null && !c.isClosed()) c.close(); } return ret; } // Takes about 2 to 6 ms on Motorola Milestone public Article getArticle(int id) { Article ret = null; Cursor c = null; try { if (!isDBAvailable()) return ret; c = db.query(TABLE_ARTICLES, null, "_id=?", new String[] { id + "" }, null, null, null, null); if (c.moveToFirst()) ret = handleArticleCursor(c); } catch (Exception e) { e.printStackTrace(); } finally { if (c != null && !c.isClosed()) c.close(); } return ret; } public Set<Label> getLabelsForArticle(int articleId) { Cursor c = null; try { // @formatter:off String sql = "SELECT f._id, f.title, 0 checked FROM " + TABLE_FEEDS + " f " + " WHERE f._id <= -11 AND" + " NOT EXISTS (SELECT * FROM " + TABLE_ARTICLES2LABELS + " a2l where f._id = a2l.labelId AND a2l.articleId = " + articleId + ")" + " UNION" + " SELECT f._id, f.title, 1 checked FROM " + TABLE_FEEDS + " f, " + TABLE_ARTICLES2LABELS + " a2l " + " WHERE f._id <= -11 AND f._id = a2l.labelId AND a2l.articleId = " + articleId; // @formatter:on if (!isDBAvailable()) return new HashSet<Label>(); c = db.rawQuery(sql, null); Set<Label> ret = new HashSet<Label>(c.getCount()); while (c.moveToNext()) { Label label = new Label(); label.id = c.getInt(0); label.caption = c.getString(1); label.checked = c.getInt(2) == 1; ret.add(label); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); } } public Feed getFeed(int id) { Feed ret = new Feed(); Cursor c = null; try { if (!isDBAvailable()) return ret; c = db.query(TABLE_FEEDS, null, "_id=?", new String[] { id + "" }, null, null, null, null); if (c.moveToFirst()) ret = handleFeedCursor(c); } finally { if (c != null && !c.isClosed()) c.close(); } return ret; } public Category getCategory(int id) { Category ret = new Category(); Cursor c = null; try { if (!isDBAvailable()) return ret; c = db.query(TABLE_CATEGORIES, null, "_id=?", new String[] { id + "" }, null, null, null, null); if (c.moveToFirst()) ret = handleCategoryCursor(c); } finally { if (c != null && !c.isClosed()) c.close(); } return ret; } public Set<Article> getUnreadArticles(int feedId) { Cursor c = null; try { if (!isDBAvailable()) return new LinkedHashSet<Article>(); c = db.query(TABLE_ARTICLES, null, "feedId=? AND isUnread>0", new String[] { feedId + "" }, null, null, null, null); Set<Article> ret = new LinkedHashSet<Article>(c.getCount()); while (c.moveToNext()) { ret.add(handleArticleCursor(c)); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); } } /** * get the map of article IDs to its update date from DB * * @param selection * A filter declaring which articles should be considered, formatted as an SQL WHERE clause (excluding * the WHERE * itself). Passing null will return all rows. * @param selectionArgs * You may include ?s in selection, which will be replaced by the values from selectionArgs, in order * that they appear in the selection. The values will be bound as Strings. * @return map of unread article IDs to its update date (may be {@code null}) */ @SuppressLint("UseSparseArrays") public Map<Integer, Long> getArticleIdUpdatedMap(String selection, String[] selectionArgs) { Map<Integer, Long> unreadUpdated = null; if (isDBAvailable()) { Cursor c = null; try { c = db.query(TABLE_ARTICLES, new String[] { "_id", "updateDate" }, selection, selectionArgs, null, null, null); unreadUpdated = new HashMap<Integer, Long>(c.getCount()); while (c.moveToNext()) { unreadUpdated.put(c.getInt(0), c.getLong(1)); } } finally { if (c != null && !c.isClosed()) c.close(); } } return unreadUpdated; } /** * 0 - Uncategorized * -1 - Special (e.g. Starred, Published, Archived, etc.) <- these are categories here o.O * -2 - Labels * -3 - All feeds, excluding virtual feeds (e.g. Labels and such) * -4 - All feeds, including virtual feeds * * @param categoryId * @return */ public Set<Feed> getFeeds(int categoryId) { Cursor c = null; try { String where = null; // categoryId = 0 if (categoryId >= 0) where = "categoryId=" + categoryId; switch (categoryId) { case -1: where = "_id IN (0, -2, -3)"; break; case -2: where = "_id < -10"; break; case -3: where = "categoryId >= 0"; break; case -4: where = null; break; } if (!isDBAvailable()) return new LinkedHashSet<Feed>(); c = db.query(TABLE_FEEDS, null, where, null, null, null, "UPPER(title) ASC"); Set<Feed> ret = new LinkedHashSet<Feed>(c.getCount()); while (c.moveToNext()) { ret.add(handleFeedCursor(c)); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); } } public Set<Category> getVirtualCategories() { Cursor c = null; try { if (!isDBAvailable()) return new LinkedHashSet<Category>(); c = db.query(TABLE_CATEGORIES, null, "_id<1", null, null, null, "_id ASC"); Set<Category> ret = new LinkedHashSet<Category>(c.getCount()); while (c.moveToNext()) { ret.add(handleCategoryCursor(c)); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); } } public Set<Category> getAllCategories() { Cursor c = null; try { if (!isDBAvailable()) return new LinkedHashSet<Category>(); c = db.query(TABLE_CATEGORIES, null, "_id>=0", null, null, null, "title ASC"); Set<Category> ret = new LinkedHashSet<Category>(c.getCount()); while (c.moveToNext()) { ret.add(handleCategoryCursor(c)); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); } } public int getUnreadCountOld(int id, boolean isCat) { int ret = 0; if (isCat && id >= 0) { // Only do this for real categories for now for (Feed f : getFeeds(id)) { // Recurse into all feeds of this category and add the unread-count ret += getUnreadCount(f.id, false); } } else { // Read count for given feed Cursor c = null; try { if (!isDBAvailable()) return ret; c = db.query(isCat ? TABLE_CATEGORIES : TABLE_FEEDS, new String[] { "unread" }, "_id=" + id, null, null, null, null, null); if (c.moveToFirst()) ret = c.getInt(0); } finally { if (c != null && !c.isClosed()) c.close(); } } return ret; } public int getUnreadCount(int id, boolean isCat) { int ret = 0; StringBuilder selection = new StringBuilder("isUnread>0"); String[] selectionArgs = new String[] { String.valueOf(id) }; if (isCat && id >= 0) { // real categories selection.append(" and feedId in (select _id from feeds where categoryId=?)"); } else { if (id < 0) { // virtual categories switch (id) { // All Articles case Data.VCAT_ALL: selectionArgs = null; break; // Fresh Articles case Data.VCAT_FRESH: selection.append(" and updateDate>?"); selectionArgs = new String[] { String.valueOf(new Date().getTime() - Controller.getInstance().getFreshArticleMaxAge()) }; break; // Published Articles case Data.VCAT_PUB: selection.append(" and isPublished>0"); selectionArgs = null; break; // Starred Articles case Data.VCAT_STAR: selection.append(" and isStarred>0"); selectionArgs = null; break; default: // Probably a label... selection.append(" and feedId=?"); } } else { // feeds selection.append(" and feedId=?"); } } // Read count for given feed Cursor c = null; try { if (!isDBAvailable()) return ret; c = db.query(TABLE_ARTICLES, new String[] { "count(*)" }, selection.toString(), selectionArgs, null, null, null, null); if (c.moveToFirst()) ret = c.getInt(0); } finally { if (c != null && !c.isClosed()) c.close(); } return ret; } @SuppressLint("UseSparseArrays") public Map<Integer, String> getMarked(String mark, int status) { Cursor c = null; try { if (!isDBAvailable()) return new HashMap<Integer, String>(); c = db.query(TABLE_MARK, new String[] { "id", MARK_NOTE }, mark + "=" + status, null, null, null, null, null); Map<Integer, String> ret = new HashMap<Integer, String>(c.getCount()); while (c.moveToNext()) { ret.put(c.getInt(0), c.getString(1)); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); } } /** * remove specified mark in the temporary mark table for specified * articles and then cleanup this table * * @param ids * article IDs, which mark should be reseted * @param mark * article mark to be reseted */ public void setMarked(Map<Integer, String> ids, String mark) { if (!isDBAvailable()) return; db.beginTransaction(); try { ContentValues cv = new ContentValues(1); for (String idList : StringSupport.convertListToString(ids.keySet(), 1000)) { cv.putNull(mark); db.update(TABLE_MARK, cv, "id IN(" + idList + ")", null); db.delete(TABLE_MARK, "isUnread IS null AND isStarred IS null AND isPublished IS null", null); } // Insert notes afterwards and only if given note is not null cv = new ContentValues(1); for (Integer id : ids.keySet()) { String note = ids.get(id); if (note == null || note.equals("")) continue; cv.put(MARK_NOTE, note); db.update(TABLE_MARK, cv, "id=" + id, null); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } // ******************************************* private static Article handleArticleCursor(Cursor c) { // @formatter:off Article ret = new Article( c.getInt(0), // _id c.getInt(1), // feedId c.getString(2), // title (c.getInt(3) != 0), // isUnread c.getString(4), // articleUrl c.getString(5), // articleCommentUrl new Date(c.getLong(6)), // updateDate c.getString(7), // content parseAttachments(c.getString(8)), // attachments (c.getInt(9) != 0), // isStarred (c.getInt(10) != 0), // isPublished c.getInt(11), // cachedImages, parseArticleLabels(c.getString(12)),// Labels c.getString(13) // Author ); // @formatter:on try { ret.cachedImages = c.getInt(11); } catch (Exception e) { // skip } return ret; } private static Feed handleFeedCursor(Cursor c) { // @formatter:off Feed ret = new Feed( c.getInt(0), // _id c.getInt(1), // categoryId c.getString(2), // title c.getString(3), // url c.getInt(4)); // unread // @formatter:on return ret; } private static Category handleCategoryCursor(Cursor c) { // @formatter:off Category ret = new Category( c.getInt(0), // _id c.getString(1), // title c.getInt(2)); // unread // @formatter:on return ret; } private static RemoteFile handleRemoteFileCursor(Cursor c) { // @formatter:off RemoteFile ret = new RemoteFile( c.getInt(0), // id c.getString(1), // url c.getInt (2), // length c.getString (3), // ext new Date(c.getLong(4)), // updateDate (c.getInt (5) != 0) // cached ); // @formatter:on return ret; } private static Set<String> parseAttachments(String att) { Set<String> ret = new LinkedHashSet<String>(); if (att == null) return ret; for (String s : att.split(";")) { ret.add(s); } return ret; } /* * Parse labels from string of the form "label;;label;;...;;label" where each label is of the following format: * "caption;forground;background" */ private static Set<Label> parseArticleLabels(String labelStr) { Set<Label> ret = new LinkedHashSet<Label>(); if (labelStr == null) return ret; int i = 0; for (String s : labelStr.split("---")) { String[] l = s.split(";"); if (l.length > 0) { i++; Label label = new Label(); label.id = i; label.checked = true; label.caption = l[0]; if (l.length > 1 && l[1].startsWith("#")) label.foregroundColor = l[1]; if (l.length > 2 && l[1].startsWith("#")) label.backgroundColor = l[2]; ret.add(label); } } return ret; } public ArrayList<Article> queryArticlesForImagecache() { if (!isDBAvailable()) return null; Cursor c = null; try { c = db.query(TABLE_ARTICLES, new String[] { "_id", "content", "attachments" }, "cachedImages IS NULL AND isUnread>0", null, null, null, null, "1000"); ArrayList<Article> ret = new ArrayList<Article>(c.getCount()); while (c.moveToNext()) { Article a = new Article(); a.id = c.getInt(0); a.content = c.getString(1); a.attachments = parseAttachments(c.getString(2)); ret.add(a); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); } } /** * insert given remote files into DB and link them with given article * * @param articleId * "parent" article * @param fileUrls * array of remote file URLs */ public void insertArticleFiles(int articleId, String[] fileUrls) { if (isDBAvailable()) { db.beginTransaction(); try { for (String url : fileUrls) { long remotefileId = insertRemoteFile(url); if (remotefileId != 0) insertRemoteFile2Article(remotefileId, articleId); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } } /** * get the DB object representing remote file by its URL * * @param url * remote file URL * * @return remote file object from DB */ public RemoteFile getRemoteFile(String url) { RemoteFile rf = null; if (isDBAvailable()) { Cursor c = null; try { c = db.query(TABLE_REMOTEFILES, null, "url=?", new String[] { url }, null, null, null, null); if (c.moveToFirst()) rf = handleRemoteFileCursor(c); } catch (Exception e) { e.printStackTrace(); } finally { if (c != null && !c.isClosed()) c.close(); } } return rf; } /** * get remote files for given article * * @param articleId * article, which remote files should be found * * @return collection of remote file objects from DB or {@code null} */ public Collection<RemoteFile> getRemoteFiles(int articleId) { ArrayList<RemoteFile> rfs = null; if (isDBAvailable()) { Cursor c = null; try { c = db.rawQuery(" SELECT r.*" // @formatter:off + " FROM " + TABLE_REMOTEFILES + " r," + TABLE_REMOTEFILE2ARTICLE + " m, " + TABLE_ARTICLES + " a" + " WHERE m.remotefileId=r.id" + " AND m.articleId=a._id" + " AND a._id=?", // @formatter:on new String[] { String.valueOf(articleId) }); rfs = new ArrayList<RemoteFile>(c.getCount()); while (c.moveToNext()) { rfs.add(handleRemoteFileCursor(c)); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null && !c.isClosed()) c.close(); } } return rfs; } /** * get remote files for given articles * * @param whereClause * the WHERE clause to apply when selecting. * @param whereArgs * You may include ?s in the where clause, which * will be replaced by the values from whereArgs. The values * will be bound as Strings. * * @param uniqOnly * if set to {@code true}, then only remote files, which are referenced by given articles only will be * returned, otherwise all remote files referenced by given articles will be found (even those, which are * referenced also by some other articles) * * @return collection of remote file objects from DB or {@code null} */ public Collection<RemoteFile> getRemoteFilesForArticles(String whereClause, String[] whereArgs, boolean uniqOnly) { ArrayList<RemoteFile> rfs = null; if (isDBAvailable()) { Cursor c = null; try { StringBuilder uniqRestriction = new StringBuilder(); String[] queryArgs = whereArgs; if (uniqOnly) { // @formatter:off uniqRestriction.append ( " AND m.remotefileId NOT IN (" ).append( " SELECT remotefileId" ).append( " FROM " ).append( TABLE_REMOTEFILE2ARTICLE ).append( " WHERE remotefileId IN (" ).append( " SELECT remotefileId" ).append( " FROM " ).append( TABLE_REMOTEFILE2ARTICLE ).append( " WHERE articleId IN (" ).append( " SELECT _id" ).append( " FROM " ).append( TABLE_ARTICLES ).append( " WHERE " ).append( whereClause ).append( " )" ).append( " GROUP BY remotefileId)" ).append( " AND articleId NOT IN (" ).append( " SELECT _id" ).append( " FROM " ).append( TABLE_ARTICLES ).append( " WHERE " ).append( whereClause ).append( " )" ).append( " GROUP by remotefileId)" ); // @formatter:on // because we are using whereClause twice in uniqRestriction, then we should also extend queryArgs, // which will be used in query if (whereArgs != null) { int initialArgLength = whereArgs.length; queryArgs = new String[initialArgLength * 3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < initialArgLength; j++) queryArgs[i * initialArgLength + j] = whereArgs[j]; } } } StringBuilder query = new StringBuilder(); // @formatter:off query.append ( " SELECT r.*" ).append( " FROM " ).append( TABLE_REMOTEFILES + " r," ).append( TABLE_REMOTEFILE2ARTICLE + " m, " ).append( TABLE_ARTICLES + " a" ).append( " WHERE m.remotefileId=r.id" ).append( " AND m.articleId=a._id" ).append( " AND a._id IN (" ).append( " SELECT _id FROM " ).append( TABLE_ARTICLES ).append( " WHERE " ).append( whereClause ).append( " )" ).append( uniqRestriction ).append( " GROUP BY r.id" ); // @formatter:on long time = System.currentTimeMillis(); c = db.rawQuery(query.toString(), queryArgs); rfs = new ArrayList<RemoteFile>(); while (c.moveToNext()) { rfs.add(handleRemoteFileCursor(c)); } Log.d(TAG, "Query in getRemoteFilesForArticles took " + (System.currentTimeMillis() - time) + "ms... (remotefiles: " + rfs.size() + ")"); } catch (Exception e) { e.printStackTrace(); } finally { if (c != null && !c.isClosed()) c.close(); } } return rfs; } /** * mark given remote file as cached/uncached and optionally specify it's file size * * @param url * remote file URL * @param cached * the cached flag * @param size * file size may be {@code null}, if so, then it will not be updated in DB */ public void markRemoteFileCached(String url, boolean cached, Long size) { if (isDBAvailable()) { db.beginTransaction(); try { ContentValues cv = new ContentValues(2); cv.put("cached", cached); if (size != null) { cv.put("length", size); } db.update(TABLE_REMOTEFILES, cv, "url=?", new String[] { url }); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } } /** * mark remote files with given IDs as non cached (cached=0) * * @param rfIds * IDs of remote files to be marked as non-cached */ public void markRemoteFilesNonCached(Collection<Integer> rfIds) { if (isDBAvailable()) { db.beginTransaction(); try { ContentValues cv = new ContentValues(1); cv.put("cached", 0); for (String ids : StringSupport.convertListToString(rfIds, 1000)) { db.update(TABLE_REMOTEFILES, cv, "id in (" + ids + ")", null); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } } /** * get summary length of remote files, which are cached * * @return summary length of remote files */ public long getCachedFilesSize() { long ret = 0; if (isDBAvailable()) { Cursor c = null; try { c = db.query(TABLE_REMOTEFILES, new String[] { "SUM(length)" }, "cached=1", null, null, null, null); if (c.moveToFirst()) ret = c.getLong(0); } finally { if (c != null && !c.isClosed()) c.close(); } } return ret; } /** * get remote files which should be deleted to free given amount of space * * @param spaceToBeFreed * amount of space (summary file size) to be freed * * @return collection of remote files, which can be deleted * to free given amount of space */ public Collection<RemoteFile> getUncacheFiles(long spaceToBeFreed) { ArrayList<RemoteFile> rfs = new ArrayList<RemoteFile>(); if (isDBAvailable()) { Cursor c = null; try { c = db.query("remotefile_sequence", null, "cached = 1", null, null, null, "ord"); long spaceToFree = spaceToBeFreed; while (spaceToFree > 0 && c.moveToNext()) { RemoteFile rf = handleRemoteFileCursor(c); spaceToFree -= rf.length; rfs.add(rf); } } finally { if (c != null && !c.isClosed()) c.close(); } } return rfs; } /** * delete remote files with given IDs * * @param idList * set of remote file IDs, which should be deleted * * @return the number of deleted rows */ public int deleteRemoteFiles(Set<Integer> idList) { int deletedCount = 0; if (isDBAvailable() && idList != null && !idList.isEmpty()) { for (String ids : StringSupport.convertListToString(idList, 400)) { deletedCount += db.delete(TABLE_REMOTEFILES, "id IN (" + ids + ")", null); } } return deletedCount; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/controllers/DBHelper.java
Java
gpl3
87,467
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.controllers; import android.app.Activity; public class ProgressBarManager { protected static final String TAG = ProgressBarManager.class.getSimpleName(); private static ProgressBarManager instance = null; private int progressIndeterminateCount = 0; // Singleton private ProgressBarManager() { } public static ProgressBarManager getInstance() { if (instance == null) { synchronized (ProgressBarManager.class) { if (instance == null) { instance = new ProgressBarManager(); } } } return instance; } public void addProgress(Activity activity) { progressIndeterminateCount++; setIndeterminateVisibility(activity); } public void removeProgress(Activity activity) { progressIndeterminateCount--; if (progressIndeterminateCount <= 0) progressIndeterminateCount = 0; setIndeterminateVisibility(activity); } public void resetProgress(Activity activity) { progressIndeterminateCount = 0; setIndeterminateVisibility(activity); } public void setIndeterminateVisibility(Activity activity) { boolean visible = (progressIndeterminateCount > 0); activity.setProgressBarIndeterminateVisibility(visible); if (!visible) { activity.setProgress(0); activity.setProgressBarVisibility(false); } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/controllers/ProgressBarManager.java
Java
gpl3
2,121
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.controllers; import java.util.ArrayList; import java.util.List; import org.ttrssreader.gui.interfaces.IDataChangedListener; import android.os.Handler; import android.os.Message; public class UpdateController { protected static final String TAG = UpdateController.class.getSimpleName(); private static UpdateController instance = null; private static List<IDataChangedListener> listeners = new ArrayList<IDataChangedListener>(); // Singleton private UpdateController() { } private static Handler handler = new Handler() { @Override public void handleMessage(Message msg) { for (IDataChangedListener listener : listeners) { listener.dataChanged(); } } }; public static UpdateController getInstance() { if (instance == null) { synchronized (UpdateController.class) { if (instance == null) { instance = new UpdateController(); } } } return instance; } public void registerActivity(IDataChangedListener listener) { listeners.add(listener); } public void unregisterActivity(IDataChangedListener listener) { listeners.remove(listener); } public void notifyListeners() { handler.sendEmptyMessage(0); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/controllers/UpdateController.java
Java
gpl3
1,938
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.controllers; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashSet; import java.util.Set; import org.stringtemplate.v4.ST; import org.ttrssreader.R; import org.ttrssreader.gui.CategoryActivity; import org.ttrssreader.gui.FeedHeadlineActivity; import org.ttrssreader.gui.MenuActivity; import org.ttrssreader.imageCache.ImageCache; import org.ttrssreader.net.JSONConnector; import org.ttrssreader.net.JavaJSONConnector; import org.ttrssreader.net.deprecated.ApacheJSONConnector; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.SSLUtils; import org.ttrssreader.utils.Utils; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; /** * Not entirely sure why this is called the "Controller". Actually, in terms of MVC, it isn't the controller. There * isn't one in here but it's called like that and I don't have a better name so we stay with it. */ public class Controller implements OnSharedPreferenceChangeListener { protected static final String TAG = Controller.class.getSimpleName(); public final static String JSON_END_URL = "api/index.php"; private final static char TEMPLATE_DELIMITER_START = '$'; private final static char TEMPLATE_DELIMITER_END = '$'; private static final String MARKER_ALIGN = "TEXT_ALIGN_MARKER"; private static final String MARKER_CACHE_DIR = "CACHE_DIR_MARKER"; private static final String MARKER_CACHED_IMAGES = "CACHED_IMAGES_MARKER"; private static final String MARKER_JS = "JS_MARKER"; private static final String MARKER_THEME = "THEME_MARKER"; private static final String MARKER_LANG = "LANG_MARKER"; private static final String MARKER_TOP_NAV = "TOP_NAVIGATION_MARKER"; private static final String MARKER_CONTENT = "CONTENT_MARKER"; private static final String MARKER_BOTTOM_NAV = "BOTTOM_NAVIGATION_MARKER"; public static final int THEME_DARK = 1; public static final int THEME_LIGHT = 2; public static final int THEME_BLACK = 3; public static final int THEME_WHITE = 4; private Context context; private WifiManager wifiManager; private JSONConnector ttrssConnector; private static final Object lockConnector = new Object(); private ImageCache imageCache = null; private boolean isHeadless = false; private static final Object lockImageCache = new Object(); private static Boolean initialized = false; private static final Object lockInitialize = new Object(); private SharedPreferences prefs = null; private static boolean preferencesChanged = false; private String url = null; private String username = null; private String password = null; private String httpUsername = null; private String httpPassword = null; private Boolean useHttpAuth = null; private Boolean trustAllSsl = null; private Boolean trustAllHosts = null; private Boolean useOldConnector; private Boolean useKeystore = null; private String keystorePassword = null; private Boolean useOfALazyServer = null; private Boolean openUrlEmptyArticle = null; private Boolean useVolumeKeys = null; private Boolean loadImages = null; private Boolean invertBrowsing = null; private Boolean goBackAfterMarkAllRead = null; private Boolean hideActionbar = null; private Boolean workOffline = null; private Boolean allowTabletLayout = null; private Integer textZoom = null; private Boolean supportZoomControls = null; private Boolean allowHyphenation = null; private String hyphenationLanguage = null; private Boolean showVirtual = null; private Integer showButtonsMode = null; private Boolean onlyUnread = null; private Boolean onlyDisplayCachedImages = null; private Boolean invertSortArticlelist = null; private Boolean invertSortFeedscats = null; private Boolean alignFlushLeft = null; private Boolean dateTimeSystem = null; private String dateString = null; private String timeString = null; private String dateTimeString = null; private Integer theme = null; private String saveAttachment = null; private String cacheFolder = null; private Integer cacheFolderMaxSize = null; private Integer cacheImageMaxSize = null; private Integer cacheImageMinSize = null; private Boolean deleteDbScheduled = null; private Boolean cacheImagesOnStartup = null; private Boolean cacheImagesOnlyWifi = null; private Boolean onlyUseWifi = null; private Boolean noCrashreports = null; private Boolean noCrashreportsUntilUpdate = null; private Long appVersionCheckTime = null; private Integer appLatestVersion = null; private String lastVersionRun = null; private Boolean newInstallation = false; private Long freshArticleMaxAge = null; private Long freshArticleMaxAgeDate = null; private Integer sinceId = null; private Long lastSync = null; private Long lastCleanup = null; private Boolean lowMemory = false; public volatile Set<Integer> lastOpenedFeeds = new HashSet<Integer>(); public volatile Set<Integer> lastOpenedArticles = new HashSet<Integer>(); // Article-View-Stuff public static String htmlTemplate = ""; private static final Object lockHtmlTemplate = new Object(); public static int relSwipeMinDistance; public static int relSwipeMaxOffPath; public static int relSwipteThresholdVelocity; public static int displayHeight; public static int displayWidth; public static boolean isTablet = false; private boolean scheduledRestart = false; // Singleton (see http://stackoverflow.com/a/11165926) private Controller() { } private static class InstanceHolder { private static final Controller instance = new Controller(); } public static Controller getInstance() { return InstanceHolder.instance; } public void checkAndInitializeController(final Context context, final Display display) { synchronized (lockInitialize) { this.context = context; this.wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!initialized) { initializeController(display); initialized = true; } } } private void initializeController(final Display display) { prefs = PreferenceManager.getDefaultSharedPreferences(context); // Initially read absolutely necessary preferences: sizeVerticalCategory = prefs.getInt(SIZE_VERTICAL_CATEGORY, -1); sizeHorizontalCategory = prefs.getInt(SIZE_HORIZONTAL_CATEGORY, -1); sizeVerticalHeadline = prefs.getInt(SIZE_VERTICAL_HEADLINE, -1); sizeHorizontalHeadline = prefs.getInt(SIZE_HORIZONTAL_HEADLINE, -1); // Check for new installation if (!prefs.contains(Constants.URL) && !prefs.contains(Constants.LAST_VERSION_RUN)) { newInstallation = true; } // Attempt to initialize some stuff in a background-thread to reduce loading time. Start a login-request // separately because this takes some time. Also initialize SSL-Stuff since the login needs this. new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... params) { try { if (Controller.getInstance().trustAllHosts()) { // Ignore if Certificate matches host: SSLUtils.trustAllHost(); } if (Controller.getInstance().useKeystore()) { // Trust certificates from keystore: SSLUtils.initPrivateKeystore(Controller.getInstance().getKeystorePassword()); } else if (Controller.getInstance().trustAllSsl()) { // Trust all certificates: SSLUtils.trustAllCert(); } else { // Normal certificate-checks: SSLUtils.initSslSocketFactory(null, null); } } catch (Exception e) { e.printStackTrace(); } // This will be accessed when displaying an article or starting the imageCache. When caching it is done // anyway so we can just do it in background and the ImageCache starts once it is done. getImageCache(); // Only need once we are displaying the feed-list or an article... refreshDisplayMetrics(display); // Loads all article and webview related resources reloadTheme(); enableHttpResponseCache(context); return null; } }.execute(); } private void reloadTheme() { // Article-Prefetch-Stuff from Raw-Ressources and System ST htmlTmpl = new ST(context.getResources().getString(R.string.HTML_TEMPLATE), TEMPLATE_DELIMITER_START, TEMPLATE_DELIMITER_END); // Replace alignment-marker with the requested layout, align:left or justified String replaceAlign; if (alignFlushLeft()) { replaceAlign = context.getResources().getString(R.string.ALIGN_LEFT); } else { replaceAlign = context.getResources().getString(R.string.ALIGN_JUSTIFY); } String javascript = ""; String lang = ""; if (allowHyphenation()) { ST javascriptST = new ST(context.getResources().getString(R.string.JAVASCRIPT_HYPHENATION_TEMPLATE), TEMPLATE_DELIMITER_START, TEMPLATE_DELIMITER_END); lang = hyphenationLanguage(); javascriptST.add(MARKER_LANG, lang); javascript = javascriptST.render(); } String buttons = ""; if (showButtonsMode() == Constants.SHOW_BUTTONS_MODE_HTML) buttons = context.getResources().getString(R.string.BOTTOM_NAVIGATION_TEMPLATE); htmlTmpl.add(MARKER_ALIGN, replaceAlign); htmlTmpl.add(MARKER_THEME, context.getResources().getString(getThemeHTML())); htmlTmpl.add(MARKER_CACHE_DIR, cacheFolder()); htmlTmpl.add(MARKER_CACHED_IMAGES, context.getResources().getString(R.string.CACHED_IMAGES_TEMPLATE)); htmlTmpl.add(MARKER_JS, javascript); htmlTmpl.add(MARKER_LANG, lang); htmlTmpl.add(MARKER_TOP_NAV, context.getResources().getString(R.string.TOP_NAVIGATION_TEMPLATE)); htmlTmpl.add(MARKER_CONTENT, context.getResources().getString(R.string.CONTENT_TEMPLATE)); htmlTmpl.add(MARKER_BOTTOM_NAV, buttons); // This is only needed once an article is displayed synchronized (lockHtmlTemplate) { htmlTemplate = htmlTmpl.render(); } } /** * Enables HTTP response caching on devices that support it, see * http://android-developers.blogspot.de/2011/09/androids-http-clients.html * * @param context */ private void enableHttpResponseCache(Context context) { try { long httpCacheSize = 10 * 1024 * 1024; // 10 MiB File httpCacheDir = new File(context.getCacheDir(), "http"); Class.forName("android.net.http.HttpResponseCache").getMethod("install", File.class, long.class) .invoke(null, httpCacheDir, httpCacheSize); } catch (Exception httpResponseCacheNotAvailable) { } } public static void refreshDisplayMetrics(Display display) { if (display == null) return; DisplayMetrics dm = new DisplayMetrics(); display.getMetrics(dm); int SWIPE_MIN_DISTANCE = 120; int SWIPE_MAX_OFF_PATH = 250; int SWIPE_THRESHOLD_VELOCITY = 200; relSwipeMinDistance = (int) (SWIPE_MIN_DISTANCE * dm.densityDpi / 160.0f); relSwipeMaxOffPath = (int) (SWIPE_MAX_OFF_PATH * dm.densityDpi / 160.0f); relSwipteThresholdVelocity = (int) (SWIPE_THRESHOLD_VELOCITY * dm.densityDpi / 160.0f); displayHeight = dm.heightPixels; displayWidth = dm.widthPixels; } // ******* CONNECTION-Options **************************** public URI uri() throws URISyntaxException { return new URI(hostname()); } public URL url() throws MalformedURLException { return new URL(hostname()); } public String hostname() { // Load from Wifi-Preferences: String key = getStringWithSSID(Constants.URL, getCurrentSSID(wifiManager)); if (prefs.contains(key)) url = prefs.getString(key, Constants.URL_DEFAULT); else url = prefs.getString(Constants.URL, Constants.URL_DEFAULT); if (!url.endsWith(JSON_END_URL)) { if (!url.endsWith("/")) { url += "/"; } url += JSON_END_URL; } return url; } public String username() { // Load from Wifi-Preferences: String key = getStringWithSSID(Constants.USERNAME, getCurrentSSID(wifiManager)); if (prefs.contains(key)) username = prefs.getString(key, Constants.EMPTY); else username = prefs.getString(Constants.USERNAME, Constants.EMPTY); return username; } public String password() { // Load from Wifi-Preferences: String key = getStringWithSSID(Constants.PASSWORD, getCurrentSSID(wifiManager)); if (prefs.contains(key)) password = prefs.getString(key, Constants.EMPTY); else password = prefs.getString(Constants.PASSWORD, Constants.EMPTY); return password; } public boolean useHttpAuth() { if (useHttpAuth == null) useHttpAuth = prefs.getBoolean(Constants.USE_HTTP_AUTH, Constants.USE_HTTP_AUTH_DEFAULT); return useHttpAuth; } public String httpUsername() { if (httpUsername == null) httpUsername = prefs.getString(Constants.HTTP_USERNAME, Constants.EMPTY); return httpUsername; } public String httpPassword() { if (httpPassword == null) httpPassword = prefs.getString(Constants.HTTP_PASSWORD, Constants.EMPTY); return httpPassword; } public boolean useKeystore() { if (useKeystore == null) useKeystore = prefs.getBoolean(Constants.USE_KEYSTORE, Constants.USE_KEYSTORE_DEFAULT); return useKeystore; } public boolean trustAllSsl() { if (trustAllSsl == null) trustAllSsl = prefs.getBoolean(Constants.TRUST_ALL_SSL, Constants.TRUST_ALL_SSL_DEFAULT); return trustAllSsl; } public boolean trustAllHosts() { if (trustAllHosts == null) trustAllHosts = prefs.getBoolean(Constants.TRUST_ALL_HOSTS, Constants.TRUST_ALL_HOSTS_DEFAULT); return trustAllHosts; } private boolean useOldConnector() { if (useOldConnector == null) useOldConnector = prefs.getBoolean(Constants.USE_OLD_CONNECTOR, Constants.USE_OLD_CONNECTOR_DEFAULT); return useOldConnector; } public JSONConnector getConnector() { // Initialized inside initializeController(); if (ttrssConnector != null) { return ttrssConnector; } else { synchronized (lockConnector) { if (ttrssConnector == null) { if (useOldConnector()) { ttrssConnector = new ApacheJSONConnector(context); } else { ttrssConnector = new JavaJSONConnector(context); } } } if (ttrssConnector != null) return ttrssConnector; else throw new RuntimeException("Connector could not be initialized."); } } public ImageCache getImageCache() { return getImageCache(true); } public ImageCache getImageCache(boolean wait) { if (imageCache == null && wait) { synchronized (lockImageCache) { if (imageCache == null) { imageCache = new ImageCache(1000, cacheFolder()); if (!imageCache.enableDiskCache()) { imageCache = null; } } } } return imageCache; } public String getKeystorePassword() { if (keystorePassword == null) keystorePassword = prefs.getString(Constants.KEYSTORE_PASSWORD, Constants.EMPTY); return keystorePassword; } public boolean isHeadless() { return isHeadless; } public void setHeadless(boolean isHeadless) { this.isHeadless = isHeadless; } // ******* USAGE-Options **************************** public boolean lazyServer() { // Load from Wifi-Preferences: String key = getStringWithSSID(Constants.USE_OF_A_LAZY_SERVER, getCurrentSSID(wifiManager)); if (prefs.contains(key)) useOfALazyServer = prefs.getBoolean(key, Constants.USE_OF_A_LAZY_SERVER_DEFAULT); else useOfALazyServer = prefs.getBoolean(Constants.USE_OF_A_LAZY_SERVER, Constants.USE_OF_A_LAZY_SERVER_DEFAULT); return useOfALazyServer; } public boolean openUrlEmptyArticle() { if (openUrlEmptyArticle == null) openUrlEmptyArticle = prefs.getBoolean(Constants.OPEN_URL_EMPTY_ARTICLE, Constants.OPEN_URL_EMPTY_ARTICLE_DEFAULT); return openUrlEmptyArticle; } public void setOpenUrlEmptyArticle(boolean openUrlEmptyArticle) { put(Constants.OPEN_URL_EMPTY_ARTICLE, openUrlEmptyArticle); this.openUrlEmptyArticle = openUrlEmptyArticle; } public boolean useVolumeKeys() { if (useVolumeKeys == null) useVolumeKeys = prefs.getBoolean(Constants.USE_VOLUME_KEYS, Constants.USE_VOLUME_KEYS_DEFAULT); return useVolumeKeys; } public void setUseVolumeKeys(boolean useVolumeKeys) { put(Constants.USE_VOLUME_KEYS, useVolumeKeys); this.useVolumeKeys = useVolumeKeys; } public boolean loadImages() { if (loadImages == null) loadImages = prefs.getBoolean(Constants.LOAD_IMAGES, Constants.LOAD_IMAGES_DEFAULT); return loadImages; } public void setLoadImages(boolean loadImages) { put(Constants.LOAD_IMAGES, loadImages); this.loadImages = loadImages; } public boolean invertBrowsing() { if (invertBrowsing == null) invertBrowsing = prefs.getBoolean(Constants.INVERT_BROWSING, Constants.INVERT_BROWSING_DEFAULT); return invertBrowsing; } public void setInvertBrowsing(boolean invertBrowsing) { put(Constants.INVERT_BROWSING, invertBrowsing); this.invertBrowsing = invertBrowsing; } public boolean workOffline() { if (workOffline == null) workOffline = prefs.getBoolean(Constants.WORK_OFFLINE, Constants.WORK_OFFLINE_DEFAULT); return workOffline; } public void setWorkOffline(boolean workOffline) { put(Constants.WORK_OFFLINE, workOffline); this.workOffline = workOffline; } public boolean goBackAfterMarkAllRead() { if (goBackAfterMarkAllRead == null) goBackAfterMarkAllRead = prefs.getBoolean(Constants.GO_BACK_AFTER_MARK_ALL_READ, Constants.GO_BACK_AFTER_MARK_ALL_READ_DEFAULT); return goBackAfterMarkAllRead; } public void setGoBackAfterMarkAllRead(boolean goBackAfterMarkAllRead) { put(Constants.GO_BACK_AFTER_MARK_ALL_READ, goBackAfterMarkAllRead); this.goBackAfterMarkAllRead = goBackAfterMarkAllRead; } public boolean hideActionbar() { if (hideActionbar == null) hideActionbar = prefs.getBoolean(Constants.HIDE_ACTIONBAR, Constants.HIDE_ACTIONBAR_DEFAULT); return hideActionbar; } public void setHideActionbar(boolean hideActionbar) { put(Constants.HIDE_ACTIONBAR, hideActionbar); this.hideActionbar = hideActionbar; } public boolean allowTabletLayout() { if (allowTabletLayout == null) allowTabletLayout = prefs.getBoolean(Constants.ALLOW_TABLET_LAYOUT, Constants.ALLOW_TABLET_LAYOUT_DEFAULT); return allowTabletLayout; } public void setAllowTabletLayout(boolean allowTabletLayout) { put(Constants.ALLOW_TABLET_LAYOUT, allowTabletLayout); this.allowTabletLayout = allowTabletLayout; } // ******* DISPLAY-Options **************************** public int textZoom() { if (textZoom == null) textZoom = prefs.getInt(Constants.TEXT_ZOOM, Constants.TEXT_ZOOM_DEFAULT); return textZoom; } public void setTextZoom(int textZoom) { put(Constants.TEXT_ZOOM, textZoom); this.textZoom = textZoom; } public boolean supportZoomControls() { if (supportZoomControls == null) supportZoomControls = prefs.getBoolean(Constants.SUPPORT_ZOOM_CONTROLS, Constants.SUPPORT_ZOOM_CONTROLS_DEFAULT); return supportZoomControls; } public void setSupportZoomControls(boolean supportZoomControls) { put(Constants.SUPPORT_ZOOM_CONTROLS, supportZoomControls); this.supportZoomControls = supportZoomControls; } public boolean allowHyphenation() { if (allowHyphenation == null) allowHyphenation = prefs.getBoolean(Constants.ALLOW_HYPHENATION, Constants.ALLOW_HYPHENATION_DEFAULT); return allowHyphenation; } public void setAllowHyphenation(boolean allowHyphenation) { put(Constants.ALLOW_HYPHENATION, allowHyphenation); this.allowHyphenation = allowHyphenation; } public String hyphenationLanguage() { if (hyphenationLanguage == null) hyphenationLanguage = prefs.getString(Constants.HYPHENATION_LANGUAGE, Constants.HYPHENATION_LANGUAGE_DEFAULT); return hyphenationLanguage; } public void setHyphenationLanguage(String hyphenationLanguage) { put(Constants.HYPHENATION_LANGUAGE, hyphenationLanguage); this.hyphenationLanguage = hyphenationLanguage; } public boolean showVirtual() { if (showVirtual == null) showVirtual = prefs.getBoolean(Constants.SHOW_VIRTUAL, Constants.SHOW_VIRTUAL_DEFAULT); return showVirtual; } public void setDisplayVirtuals(boolean displayVirtuals) { put(Constants.SHOW_VIRTUAL, displayVirtuals); this.showVirtual = displayVirtuals; } public Integer showButtonsMode() { if (showButtonsMode == null) showButtonsMode = Integer.parseInt(prefs.getString(Constants.SHOW_BUTTONS_MODE, Constants.SHOW_BUTTONS_MODE_DEFAULT)); return showButtonsMode; } public void setShowButtonsMode(Integer showButtonsMode) { put(Constants.SHOW_BUTTONS_MODE, showButtonsMode); this.showButtonsMode = showButtonsMode; } public boolean onlyUnread() { if (onlyUnread == null) onlyUnread = prefs.getBoolean(Constants.ONLY_UNREAD, Constants.ONLY_UNREAD_DEFAULT); return onlyUnread; } public void setDisplayOnlyUnread(boolean displayOnlyUnread) { put(Constants.ONLY_UNREAD, displayOnlyUnread); this.onlyUnread = displayOnlyUnread; } public boolean onlyDisplayCachedImages() { if (onlyDisplayCachedImages == null) onlyDisplayCachedImages = prefs.getBoolean(Constants.ONLY_CACHED_IMAGES, Constants.ONLY_CACHED_IMAGES_DEFAULT); return onlyDisplayCachedImages; } public void setDisplayCachedImages(boolean onlyDisplayCachedImages) { put(Constants.ONLY_CACHED_IMAGES, onlyDisplayCachedImages); this.onlyDisplayCachedImages = onlyDisplayCachedImages; } public boolean invertSortArticlelist() { if (invertSortArticlelist == null) invertSortArticlelist = prefs.getBoolean(Constants.INVERT_SORT_ARTICLELIST, Constants.INVERT_SORT_ARTICLELIST_DEFAULT); return invertSortArticlelist; } public void setInvertSortArticleList(boolean invertSortArticleList) { put(Constants.INVERT_SORT_ARTICLELIST, invertSortArticleList); this.invertSortArticlelist = invertSortArticleList; } public boolean invertSortFeedscats() { if (invertSortFeedscats == null) invertSortFeedscats = prefs.getBoolean(Constants.INVERT_SORT_FEEDSCATS, Constants.INVERT_SORT_FEEDSCATS_DEFAULT); return invertSortFeedscats; } public void setInvertSortFeedsCats(boolean invertSortFeedsCats) { put(Constants.INVERT_SORT_FEEDSCATS, invertSortFeedsCats); this.invertSortFeedscats = invertSortFeedsCats; } public boolean alignFlushLeft() { if (alignFlushLeft == null) alignFlushLeft = prefs.getBoolean(Constants.ALIGN_FLUSH_LEFT, Constants.ALIGN_FLUSH_LEFT_DEFAULT); return alignFlushLeft; } public void setAlignFlushLeft(boolean alignFlushLeft) { put(Constants.ALIGN_FLUSH_LEFT, alignFlushLeft); this.alignFlushLeft = alignFlushLeft; } public boolean dateTimeSystem() { if (dateTimeSystem == null) dateTimeSystem = prefs.getBoolean(Constants.DATE_TIME_SYSTEM, Constants.DATE_TIME_SYSTEM_DEFAULT); return dateTimeSystem; } public void setDateTimeSystem(boolean dateTimeSystem) { put(Constants.DATE_TIME_SYSTEM, dateTimeSystem); this.dateTimeSystem = dateTimeSystem; } public String dateString() { if (dateString == null) dateString = prefs.getString(Constants.DATE_STRING, Constants.DATE_STRING_DEFAULT); return dateString; } public void setDateString(String dateString) { put(Constants.DATE_STRING, dateString); this.dateString = dateString; } public String timeString() { if (timeString == null) timeString = prefs.getString(Constants.TIME_STRING, Constants.TIME_STRING_DEFAULT); return timeString; } public void setTimeString(String timeString) { put(Constants.TIME_STRING, timeString); this.timeString = timeString; } public String dateTimeString() { if (dateTimeString == null) dateTimeString = prefs.getString(Constants.DATE_TIME_STRING, Constants.DATE_TIME_STRING_DEFAULT); return dateTimeString; } public void setDateTimeString(String dateTimeString) { put(Constants.DATE_TIME_STRING, dateTimeString); this.dateTimeString = dateTimeString; } public int getTheme() { switch (getThemeInternal()) { case THEME_LIGHT: return R.style.Theme_Light; case THEME_BLACK: return R.style.Theme_Black; case THEME_WHITE: return R.style.Theme_White; case THEME_DARK: default: return R.style.Theme_Dark; } } public int getThemeInternal() { if (theme == null) theme = Integer.parseInt(prefs.getString(Constants.THEME, Constants.THEME_DEFAULT)); return theme; } public void setTheme(int theme) { this.theme = theme; put(Constants.THEME, theme + ""); } public int getThemeBackground() { switch (getThemeInternal()) { case THEME_LIGHT: return R.color.background_light; case THEME_BLACK: return R.color.background_black; case THEME_WHITE: return R.color.background_white; case THEME_DARK: default: return R.color.background_dark; } } public int getThemeFont() { switch (getThemeInternal()) { case THEME_LIGHT: return R.color.font_color_light; case THEME_BLACK: return R.color.font_color_black; case THEME_WHITE: return R.color.font_color_white; case THEME_DARK: default: return R.color.font_color_dark; } } public int getThemeHTML() { switch (getThemeInternal()) { case THEME_LIGHT: return R.string.HTML_THEME_LIGHT; case THEME_BLACK: return R.string.HTML_THEME_BLACK; case THEME_WHITE: return R.string.HTML_THEME_WHITE; case THEME_DARK: default: return R.string.HTML_THEME_DARK; } } public boolean isScheduledRestart() { return scheduledRestart; } public void setScheduledRestart(boolean scheduledRestart) { this.scheduledRestart = scheduledRestart; } // SYSTEM public String saveAttachmentPath() { if (saveAttachment == null) saveAttachment = prefs.getString(Constants.SAVE_ATTACHMENT, Constants.SAVE_ATTACHMENT_DEFAULT); return saveAttachment; } public void setSaveAttachmentPath(String saveAttachment) { put(Constants.SAVE_ATTACHMENT, saveAttachment); this.saveAttachment = saveAttachment; } public String cacheFolder() { if (cacheFolder == null) cacheFolder = prefs.getString(Constants.CACHE_FOLDER, Constants.CACHE_FOLDER_DEFAULT); if (!cacheFolder.endsWith("/")) setCacheFolder(cacheFolder + "/"); return cacheFolder; } public void setCacheFolder(String cacheFolder) { put(Constants.CACHE_FOLDER, cacheFolder); this.cacheFolder = cacheFolder; } public Integer cacheFolderMaxSize() { if (cacheFolderMaxSize == null) cacheFolderMaxSize = prefs.getInt(Constants.CACHE_FOLDER_MAX_SIZE, Constants.CACHE_FOLDER_MAX_SIZE_DEFAULT); return cacheFolderMaxSize; } public void setCacheFolderMaxSize(Integer cacheFolderMaxSize) { put(Constants.CACHE_FOLDER_MAX_SIZE, cacheFolderMaxSize); this.cacheFolderMaxSize = cacheFolderMaxSize; } public Integer cacheImageMaxSize() { if (cacheImageMaxSize == null) cacheImageMaxSize = prefs.getInt(Constants.CACHE_IMAGE_MAX_SIZE, Constants.CACHE_IMAGE_MAX_SIZE_DEFAULT); return cacheImageMaxSize; } public void setCacheImageMaxSize(Integer cacheImageMaxSize) { put(Constants.CACHE_IMAGE_MAX_SIZE, cacheImageMaxSize); this.cacheImageMaxSize = cacheImageMaxSize; } public Integer cacheImageMinSize() { if (cacheImageMinSize == null) cacheImageMinSize = prefs.getInt(Constants.CACHE_IMAGE_MIN_SIZE, Constants.CACHE_IMAGE_MIN_SIZE_DEFAULT); return cacheImageMinSize; } public void setCacheImageMinSize(Integer cacheImageMinSize) { put(Constants.CACHE_IMAGE_MIN_SIZE, cacheImageMinSize); this.cacheImageMinSize = cacheImageMinSize; } public boolean isDeleteDBScheduled() { if (deleteDbScheduled == null) deleteDbScheduled = prefs.getBoolean(Constants.DELETE_DB_SCHEDULED, Constants.DELETE_DB_SCHEDULED_DEFAULT); return deleteDbScheduled; } public void setDeleteDBScheduled(boolean isDeleteDBScheduled) { put(Constants.DELETE_DB_SCHEDULED, isDeleteDBScheduled); this.deleteDbScheduled = isDeleteDBScheduled; } public boolean cacheImagesOnStartup() { if (cacheImagesOnStartup == null) cacheImagesOnStartup = prefs.getBoolean(Constants.CACHE_IMAGES_ON_STARTUP, Constants.CACHE_IMAGES_ON_STARTUP_DEFAULT); return cacheImagesOnStartup; } public void setCacheImagesOnStartup(boolean cacheImagesOnStartup) { put(Constants.CACHE_IMAGES_ON_STARTUP, cacheImagesOnStartup); this.cacheImagesOnStartup = cacheImagesOnStartup; } public boolean cacheImagesOnlyWifi() { if (cacheImagesOnlyWifi == null) cacheImagesOnlyWifi = prefs.getBoolean(Constants.CACHE_IMAGES_ONLY_WIFI, Constants.CACHE_IMAGES_ONLY_WIFI_DEFAULT); return cacheImagesOnlyWifi; } public void setCacheImagesOnlyWifi(boolean cacheImagesOnlyWifi) { put(Constants.CACHE_IMAGES_ONLY_WIFI, cacheImagesOnlyWifi); this.cacheImagesOnlyWifi = cacheImagesOnlyWifi; } public boolean onlyUseWifi() { if (onlyUseWifi == null) onlyUseWifi = prefs.getBoolean(Constants.ONLY_USE_WIFI, Constants.ONLY_USE_WIFI_DEFAULT); return onlyUseWifi; } public void setOnlyUseWifi(boolean onlyUseWifi) { put(Constants.ONLY_USE_WIFI, onlyUseWifi); this.onlyUseWifi = onlyUseWifi; } // Returns true if noCrashreports OR noCrashreportsUntilUpdate is true. public boolean isNoCrashreports() { if (noCrashreports == null) noCrashreports = prefs.getBoolean(Constants.NO_CRASHREPORTS, Constants.NO_CRASHREPORTS_DEFAULT); if (noCrashreportsUntilUpdate == null) noCrashreportsUntilUpdate = prefs.getBoolean(Constants.NO_CRASHREPORTS_UNTIL_UPDATE, Constants.NO_CRASHREPORTS_UNTIL_UPDATE_DEFAULT); return noCrashreports || noCrashreportsUntilUpdate; } public void setNoCrashreports(boolean noCrashreports) { put(Constants.NO_CRASHREPORTS, noCrashreports); this.noCrashreports = noCrashreports; } public void setNoCrashreportsUntilUpdate(boolean noCrashreportsUntilUpdate) { put(Constants.NO_CRASHREPORTS_UNTIL_UPDATE, noCrashreportsUntilUpdate); this.noCrashreportsUntilUpdate = noCrashreportsUntilUpdate; } // ******* INTERNAL Data **************************** public long appVersionCheckTime() { if (appVersionCheckTime == null) appVersionCheckTime = prefs.getLong(Constants.APP_VERSION_CHECK_TIME, Constants.APP_VERSION_CHECK_TIME_DEFAULT); return appVersionCheckTime; } private void setAppVersionCheckTime(long appVersionCheckTime) { put(Constants.APP_VERSION_CHECK_TIME, appVersionCheckTime); this.appVersionCheckTime = appVersionCheckTime; } public int appLatestVersion() { if (appLatestVersion == null) appLatestVersion = prefs.getInt(Constants.APP_LATEST_VERSION, Constants.APP_LATEST_VERSION_DEFAULT); return appLatestVersion; } public void setAppLatestVersion(int appLatestVersion) { put(Constants.APP_LATEST_VERSION, appLatestVersion); this.appLatestVersion = appLatestVersion; setAppVersionCheckTime(System.currentTimeMillis()); // Set current time, this only changes when it has been fetched from the server } public String getLastVersionRun() { if (lastVersionRun == null) lastVersionRun = prefs.getString(Constants.LAST_VERSION_RUN, Constants.LAST_VERSION_RUN_DEFAULT); return lastVersionRun; } public void setLastVersionRun(String lastVersionRun) { put(Constants.LAST_VERSION_RUN, lastVersionRun); this.lastVersionRun = lastVersionRun; } public boolean newInstallation() { // Initialized inside initializeController(); return newInstallation; } public void setSinceId(int sinceId) { put(Constants.SINCE_ID, sinceId); this.sinceId = sinceId; } public int getSinceId() { if (sinceId == null) sinceId = prefs.getInt(Constants.SINCE_ID, Constants.SINCE_ID_DEFAULT); return sinceId; } public void setLastSync(long lastSync) { put(Constants.LAST_SYNC, lastSync); this.lastSync = lastSync; } public long getLastSync() { if (lastSync == null) lastSync = prefs.getLong(Constants.LAST_SYNC, Constants.LAST_SYNC_DEFAULT); return lastSync; } public void lowMemory(boolean lowMemory) { if (lowMemory && !this.lowMemory) Log.w(TAG, "lowMemory-Situation detected, trying to reduce memory footprint..."); this.lowMemory = lowMemory; } public boolean isLowMemory() { return lowMemory; } public void setLastCleanup(long lastCleanup) { put(Constants.LAST_CLEANUP, lastCleanup); this.lastCleanup = lastSync; } public long getLastCleanup() { if (lastCleanup == null) lastCleanup = prefs.getLong(Constants.LAST_CLEANUP, Constants.LAST_CLEANUP_DEFAULT); return lastCleanup; } private AsyncTask<Void, Void, Void> refreshPrefTask; public long getFreshArticleMaxAge() { if (freshArticleMaxAge == null) freshArticleMaxAge = prefs .getLong(Constants.FRESH_ARTICLE_MAX_AGE, Constants.FRESH_ARTICLE_MAX_AGE_DEFAULT); if (freshArticleMaxAgeDate == null) freshArticleMaxAgeDate = prefs.getLong(Constants.FRESH_ARTICLE_MAX_AGE_DATE, Constants.FRESH_ARTICLE_MAX_AGE_DATE_DEFAULT); if (freshArticleMaxAgeDate < System.currentTimeMillis() - (Utils.DAY * 2)) { // Only start task if none existing yet if (refreshPrefTask == null) { refreshPrefTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { String s = ""; try { s = Data.getInstance().getPref("FRESH_ARTICLE_MAX_AGE"); freshArticleMaxAge = Long.parseLong(s) * Utils.HOUR; put(Constants.FRESH_ARTICLE_MAX_AGE, freshArticleMaxAge); freshArticleMaxAgeDate = System.currentTimeMillis(); put(Constants.FRESH_ARTICLE_MAX_AGE_DATE, freshArticleMaxAgeDate); } catch (Exception e) { Log.d(TAG, "Pref \"FRESH_ARTICLE_MAX_AGE\" could not be fetched from server: " + s); } return null; } }; refreshPrefTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } return freshArticleMaxAge; } /* * Generic method to insert values into the preferences store */ private void put(String constant, Object o) { SharedPreferences.Editor editor = prefs.edit(); if (o instanceof String) { editor.putString(constant, (String) o); } else if (o instanceof Integer) { editor.putInt(constant, (Integer) o); } else if (o instanceof Long) { editor.putLong(constant, (Long) o); } else if (o instanceof Boolean) { editor.putBoolean(constant, (Boolean) o); } /* * The following Code is extracted from * https://code.google.com/p/zippy-android/source/browse/trunk/examples/SharedPreferencesCompat.java * * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Uses faster apply() instead of commit() if method is available if (sApplyMethod != null) { try { sApplyMethod.invoke(editor); return; } catch (InvocationTargetException unused) { // fall through } catch (IllegalAccessException unused) { // fall through } } editor.commit(); } private static final Method sApplyMethod = findApplyMethod(); private static Method findApplyMethod() { try { Class<?> cls = SharedPreferences.Editor.class; return cls.getMethod("apply"); } catch (NoSuchMethodException unused) { // fall through } return null; } /** * If provided "key" resembles a setting as declared in Constants.java the corresponding variable in this class will * be reset to null. Variable-Name ist built from the name of the field in Contants.java which holds the value from * "key" which was changed lately. */ @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // Indicate Restart of App is necessary if Theme-Pref is changed and value differs from old value: if (key.equals(Constants.THEME)) { int newTheme = Integer.parseInt(prefs.getString(key, Constants.THEME_DEFAULT)); if (newTheme != getThemeInternal()) { setTheme(newTheme); reloadTheme(); scheduledRestart = true; } } for (Field field : Constants.class.getDeclaredFields()) { // No default-values if (field.getName().endsWith(Constants.APPENDED_DEFAULT)) continue; // Only use public static fields if (!Modifier.isStatic(field.getModifiers()) || !Modifier.isPublic(field.getModifiers())) continue; String fieldName = ""; try { Object f = field.get(this); if (!(f instanceof String)) continue; if (!key.equals((String) f)) continue; // reset variable, it will be re-read on next access fieldName = Constants.constant2Var(field.getName()); Controller.class.getDeclaredField(fieldName).set(this, null); // "Declared" so also private setPreferencesChanged(true); } catch (Exception e) { Log.e(TAG, "Field not found: " + fieldName); } } } public boolean isPreferencesChanged() { return preferencesChanged; } public void setPreferencesChanged(boolean preferencesChanged) { Controller.preferencesChanged = preferencesChanged; } private static String getCurrentSSID(WifiManager wifiManager) { if (wifiManager != null && wifiManager.isWifiEnabled()) { WifiInfo info = wifiManager.getConnectionInfo(); final String ssid = info.getSSID(); return ssid == null ? "" : ssid.replace("\"", ""); } else { return null; } } private static String getStringWithSSID(String param, String wifiSSID) { if (wifiSSID == null) return param; else return wifiSSID + param; } private static final String SIZE_VERTICAL_CATEGORY = "sizeVerticalCategory"; private static final String SIZE_HORIZONTAL_CATEGORY = "sizeHorizontalCategory"; private static final String SIZE_VERTICAL_HEADLINE = "sizeVerticalHeadline"; private static final String SIZE_HORIZONTAL_HEADLINE = "sizeHorizontalHeadline"; private Integer sizeVerticalCategory; private Integer sizeHorizontalCategory; private Integer sizeVerticalHeadline; private Integer sizeHorizontalHeadline; public int getMainFrameSize(MenuActivity activity, boolean isVertical, int min, int max) { int ret = -1; if (activity instanceof CategoryActivity) { if (isVertical) { ret = sizeVerticalCategory; } else { ret = sizeHorizontalCategory; } } else if (activity instanceof FeedHeadlineActivity) { if (isVertical) { ret = sizeVerticalHeadline; } else { ret = sizeHorizontalHeadline; } } if (ret < min || ret > max) ret = (min + max) / 2; return ret; } public void setViewSize(MenuActivity activity, boolean isVertical, int size) { if (size <= 0) return; if (activity instanceof CategoryActivity) { if (isVertical) { sizeVerticalCategory = size; put(SIZE_VERTICAL_CATEGORY, size); } else { sizeHorizontalCategory = size; put(SIZE_HORIZONTAL_CATEGORY, size); } } else if (activity instanceof FeedHeadlineActivity) { if (isVertical) { sizeVerticalHeadline = size; put(SIZE_VERTICAL_HEADLINE, size); } else { sizeHorizontalHeadline = size; put(SIZE_HORIZONTAL_HEADLINE, size); } } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/controllers/Controller.java
Java
gpl3
47,638
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.preferences; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; import android.util.Log; /** * Just implement a BackupAgent for the SharedPreferences, nothing else is of importance to us. * * @author Nils Braden */ public class MyPrefsBackupAgent extends BackupAgentHelper { protected static final String TAG = MyPrefsBackupAgent.class.getSimpleName(); static final String PREFS = "org.ttrssreader_preferences"; static final String PREFS_BACKUP_KEY = "prefs"; @Override public void onCreate() { Log.e(TAG, "== DEBUG: MyPrefsBackupAgent started..."); SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS); addHelper(PREFS_BACKUP_KEY, helper); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/preferences/MyPrefsBackupAgent.java
Java
gpl3
1,347
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.preferences; import java.util.Map; import org.ttrssreader.R; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.util.Log; import android.view.Menu; import android.view.MenuItem; @SuppressWarnings("deprecation") public class ConnectionSettings extends PreferenceActivity { protected static final String TAG = ConnectionSettings.class.getSimpleName(); private static final String KEY_CONNECTION_CATEGORY = "connectionCategory"; public static final String KEY_SSID = "SSID"; private static final int MENU_DELETE = 1; private String sSID; private PreferenceCategory category; private SharedPreferences prefs = null; private Map<String, ?> prefsCache = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs_main_top); final PreferenceScreen preferenceScreen = getPreferenceScreen(); category = (PreferenceCategory) preferenceScreen.findPreference(KEY_CONNECTION_CATEGORY); prefs = PreferenceManager.getDefaultSharedPreferences(this); prefsCache = prefs.getAll(); if (getIntent().getStringExtra(KEY_SSID) != null) { // WiFi-Based Settings sSID = getIntent().getStringExtra(KEY_SSID); createDynamicSettings(sSID); } else { // Default settings createDynamicSettings(""); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, R.string.ConnectionWifiDeletePref); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (item != null && item.getItemId() == MENU_DELETE) { Editor edit = prefs.edit(); for (int i = 0; i < category.getPreferenceCount(); i++) { Preference pref = category.getPreference(i); if (prefs.contains(pref.getKey())) { edit.remove(pref.getKey()); // Remove and add again to reinitialize default values category.removePreference(pref); category.addPreference(pref); } } edit.commit(); prefsCache = prefs.getAll(); } return super.onMenuItemSelected(featureId, item); } private void createDynamicSettings(String keyPrefix) { category.setTitle(category.getTitle() + " ( Network: " + keyPrefix + " )"); Log.d(TAG, "Adding WifiPreferences..."); for (int i = 0; i < category.getPreferenceCount(); i++) { Preference pref = category.getPreference(i); String oldKey = pref.getKey(); String newKey = keyPrefix + oldKey; pref.setKey(newKey); Object defaultValue = null; if (prefsCache.containsKey(newKey)) defaultValue = prefsCache.get(newKey); pref.setDefaultValue(defaultValue); // Remove and add again to reinitialize default values category.removePreference(pref); category.addPreference(pref); Log.d(TAG, String.format(" oldKey: \"%s\" newKey: \"%s\"", oldKey, newKey)); } onContentChanged(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/preferences/ConnectionSettings.java
Java
gpl3
4,419
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.preferences; import android.content.Context; import android.preference.EditTextPreference; import android.util.AttributeSet; public class EditIntegerPreference extends EditTextPreference { public EditIntegerPreference(Context context) { super(context); } public EditIntegerPreference(Context context, AttributeSet attrs) { super(context, attrs); } public EditIntegerPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected String getPersistedString(String defaultReturnValue) { return String.valueOf(getPersistedInt(-1)); } @Override protected boolean persistString(String value) { if (value == null || value.length() == 0) return false; return persistInt(Integer.valueOf(value)); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/preferences/EditIntegerPreference.java
Java
gpl3
1,430
package org.ttrssreader.preferences; import java.io.File; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.text.InputType; import android.widget.EditText; /** * Copied from https://code.google.com/p/k9mail/ */ public class FileBrowserHelper { /** * A string array that specifies the name of the intent to use, and the scheme to use with it * when setting the data for the intent. */ private static final String[][] PICK_DIRECTORY_INTENTS = { { "org.openintents.action.PICK_DIRECTORY", "file://" }, // OI // File // Manager { "com.estrongs.action.PICK_DIRECTORY", "file://" }, // ES File Explorer { Intent.ACTION_PICK, "folder://" }, // Blackmoon File Browser (maybe others) { "com.androidworkz.action.PICK_DIRECTORY", "file://" } }; // SystemExplorer private static FileBrowserHelper instance; /** * callbackDownloadPath class to provide the result of the fallback textedit path dialog */ public interface FileBrowserFailOverCallback { /** * the user has entered a path * * @param path * the path as String */ public void onPathEntered(String path); /** * the user has cancel the inputtext dialog */ public void onCancel(); } // Singleton private FileBrowserHelper() { } public synchronized static FileBrowserHelper getInstance() { if (instance == null) { instance = new FileBrowserHelper(); } return instance; } /** * tries to open known filebrowsers. * If no filebrowser is found and fallback textdialog is shown * * @param c * the context as activity * @param startPath * : the default value, where the filebrowser will start. * if startPath = null => the default path is used * @param requestcode * : the int you will get as requestcode in onActivityResult * (only used if there is a filebrowser installed) * @param callbackDownloadPath * : the callbackDownloadPath (only used when no filebrowser is installed. * if a filebrowser is installed => override the onActivtyResult Method * * @return true: if a filebrowser has been found (the result will be in the onActivityResult * false: a fallback textinput has been shown. The Result will be sent with the callbackDownloadPath method * * */ public boolean showFileBrowserActivity(Activity c, File startPath, int requestcode, FileBrowserFailOverCallback callback) { boolean success = false; if (startPath == null) { startPath = new File(Controller.getInstance().saveAttachmentPath()); } int listIndex = 0; do { String intentAction = PICK_DIRECTORY_INTENTS[listIndex][0]; String uriPrefix = PICK_DIRECTORY_INTENTS[listIndex][1]; Intent intent = new Intent(intentAction); intent.setData(Uri.parse(uriPrefix + startPath.getPath())); try { c.startActivityForResult(intent, requestcode); success = true; } catch (ActivityNotFoundException e) { // Try the next intent in the list listIndex++; }; } while (!success && (listIndex < PICK_DIRECTORY_INTENTS.length)); if (listIndex == PICK_DIRECTORY_INTENTS.length) { // No Filebrowser is installed => show a fallback textdialog showPathTextInput(c, startPath, callback); success = false; } return success; } private void showPathTextInput(final Activity c, final File startPath, final FileBrowserFailOverCallback callback) { AlertDialog.Builder alert = new AlertDialog.Builder(c); alert.setTitle(c.getString(R.string.Utils_FileSaveTitle)); alert.setMessage(c.getString(R.string.Utils_FileSaveMessage)); final EditText input = new EditText(c); input.setInputType(InputType.TYPE_CLASS_TEXT); if (startPath != null) input.setText(startPath.toString()); alert.setView(input); alert.setPositiveButton(c.getString(R.string.Utils_OkayAction), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String path = input.getText().toString(); callback.onPathEntered(path); } }); alert.setNegativeButton(c.getString(R.string.Utils_CancelAction), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { callback.onCancel(); } }); alert.show(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/preferences/FileBrowserHelper.java
Java
gpl3
5,463
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.preferences; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import android.content.Context; import android.content.Intent; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; public class WifiConnectionSettings extends PreferenceActivity { private PreferenceCategory mWifibasedCategory; private List<WifiConfiguration> mWifiList; private WifiManager mWifiManager; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); // IMPORTANT! addPreferencesFromResource(R.xml.prefs_wifibased); final PreferenceScreen preferenceScreen = getPreferenceScreen(); mWifibasedCategory = (PreferenceCategory) preferenceScreen.findPreference("wifibasedCategory"); mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); mWifiList = mWifiManager.getConfiguredNetworks(); if (mWifiList == null) return; for (WifiConfiguration wifi : mWifiList) { // Friendly SSID-Name String ssid = wifi.SSID.replaceAll("\"", ""); // Add PreferenceScreen for each network PreferenceScreen pref = getPreferenceManager().createPreferenceScreen(this); pref.setPersistent(false); pref.setKey("wifiNetwork" + ssid); pref.setTitle(ssid); Intent intent = new Intent(this, ConnectionSettings.class); intent.putExtra(ConnectionSettings.KEY_SSID, ssid); pref.setIntent(intent); if (WifiConfiguration.Status.CURRENT == wifi.status) pref.setSummary(getResources().getString(R.string.ConnectionWifiConnected)); else pref.setSummary(getResources().getString(R.string.ConnectionWifiNotInRange)); mWifibasedCategory.addPreference(pref); } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/preferences/WifiConnectionSettings.java
Java
gpl3
2,778
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.preferences; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.Utils; import android.content.SharedPreferences; import android.os.Environment; public class Constants { public static final String EMPTY = ""; public static final String APPENDED_DEFAULT = "_DEFAULT"; static { StringBuilder sbAttachments = new StringBuilder(); sbAttachments.append(Environment.getExternalStorageDirectory()).append(File.separator) .append(FileUtils.SDCARD_PATH_FILES); SAVE_ATTACHMENT_DEFAULT = sbAttachments.toString(); StringBuilder sbCache = new StringBuilder(); sbCache.append(Environment.getExternalStorageDirectory()).append(File.separator) .append(FileUtils.SDCARD_PATH_CACHE); CACHE_FOLDER_DEFAULT = sbCache.toString(); } // Connection public static final String URL = "ConnectionUrlPreference"; public static final String USERNAME = "ConnectionUsernamePreference"; public static final String PASSWORD = "ConnectionPasswordPreference"; public static final String USE_HTTP_AUTH = "ConnectionHttpPreference"; public static final String HTTP_USERNAME = "ConnectionHttpUsernamePreference"; public static final String HTTP_PASSWORD = "ConnectionHttpPasswordPreference"; public static final String TRUST_ALL_SSL = "ConnectionSSLPreference"; public static final String TRUST_ALL_HOSTS = "ConnectionTrustHostsPreference"; public static final String USE_OLD_CONNECTOR = "ConnectionUseOldConnector"; public static final String USE_KEYSTORE = "ConnectionUseKeystorePreference"; public static final String KEYSTORE_PASSWORD = "ConnectionKeystorePasswordPreference"; public static final String USE_OF_A_LAZY_SERVER = "ConnectionLazyServerPreference"; // Connection Default Values public static final String URL_DEFAULT = "http://localhost/"; public static final boolean USE_HTTP_AUTH_DEFAULT = false; public static final boolean TRUST_ALL_SSL_DEFAULT = false; public static final boolean TRUST_ALL_HOSTS_DEFAULT = false; public static final boolean USE_OLD_CONNECTOR_DEFAULT = false; public static final boolean USE_KEYSTORE_DEFAULT = false; public static final boolean USE_OF_A_LAZY_SERVER_DEFAULT = false; // Usage public static final String OPEN_URL_EMPTY_ARTICLE = "UsageOpenUrlEmptyArticlePreference"; public static final String USE_VOLUME_KEYS = "UsageUseVolumeKeysPreference"; public static final String LOAD_IMAGES = "DisplayLoadImagesPreference"; public static final String INVERT_BROWSING = "InvertBrowseArticlesPreference"; public static final String WORK_OFFLINE = "UsageWorkOfflinePreference"; public static final String GO_BACK_AFTER_MARK_ALL_READ = "GoBackAfterMarkAllReadPreference"; public static final String HIDE_ACTIONBAR = "HideActionbarPreference"; public static final String ALLOW_TABLET_LAYOUT = "AllowTabletLayoutPreference"; // Usage Default Values public static final boolean OPEN_URL_EMPTY_ARTICLE_DEFAULT = false; public static final boolean USE_VOLUME_KEYS_DEFAULT = false; public static final boolean LOAD_IMAGES_DEFAULT = true; public static final boolean INVERT_BROWSING_DEFAULT = false; public static final boolean WORK_OFFLINE_DEFAULT = false; public static final boolean GO_BACK_AFTER_MARK_ALL_READ_DEFAULT = false; public static final boolean HIDE_ACTIONBAR_DEFAULT = true; public static final boolean ALLOW_TABLET_LAYOUT_DEFAULT = true; // Display public static final String HEADLINE_SIZE = "HeadlineSizePreference"; public static final String TEXT_ZOOM = "TextZoomPreference"; public static final String SUPPORT_ZOOM_CONTROLS = "SupportZoomControlsPreference"; public static final String ALLOW_HYPHENATION = "AllowHyphenationPreference"; public static final String HYPHENATION_LANGUAGE = "HyphenationLanguagePreference"; public static final String SHOW_VIRTUAL = "DisplayShowVirtualPreference"; public static final String SHOW_BUTTONS_MODE = "ShowButtonsModePreference"; public static final String ONLY_UNREAD = "DisplayShowUnreadOnlyPreference"; public static final String ONLY_CACHED_IMAGES = "DisplayShowCachedImagesPreference"; public static final String INVERT_SORT_ARTICLELIST = "InvertSortArticlelistPreference"; public static final String INVERT_SORT_FEEDSCATS = "InvertSortFeedscatsPreference"; public static final String ALIGN_FLUSH_LEFT = "DisplayAlignFlushLeftPreference"; public static final String DATE_TIME_SYSTEM = "DisplayDateTimeFormatSystemPreference"; public static final String DATE_STRING = "DisplayDateFormatPreference"; public static final String TIME_STRING = "DisplayTimeFormatPreference"; public static final String DATE_TIME_STRING = "DisplayDateTimeFormatPreference"; public static final String THEME = "DisplayThemePreference"; // Display Default Values public static final int HEADLINE_SIZE_DEFAULT = 16; public static final int TEXT_ZOOM_DEFAULT = 100; public static final boolean SUPPORT_ZOOM_CONTROLS_DEFAULT = true; public static final boolean ALLOW_HYPHENATION_DEFAULT = false; public static final String HYPHENATION_LANGUAGE_DEFAULT = "en-gb"; public static final boolean SHOW_VIRTUAL_DEFAULT = true; public static final String SHOW_BUTTONS_MODE_DEFAULT = "0"; public static final int SHOW_BUTTONS_MODE_NONE = 0; public static final int SHOW_BUTTONS_MODE_ALLWAYS = 1; public static final int SHOW_BUTTONS_MODE_HTML = 2; public static final boolean ONLY_UNREAD_DEFAULT = false; public static final boolean ONLY_CACHED_IMAGES_DEFAULT = false; public static final boolean INVERT_SORT_ARTICLELIST_DEFAULT = false; public static final boolean INVERT_SORT_FEEDSCATS_DEFAULT = false; public static final boolean ALIGN_FLUSH_LEFT_DEFAULT = false; public static final boolean DATE_TIME_SYSTEM_DEFAULT = true; public static final String DATE_STRING_DEFAULT = "dd.MM.yyyy"; public static final String TIME_STRING_DEFAULT = "kk:mm"; public static final String DATE_TIME_STRING_DEFAULT = "dd.MM.yyyy kk:mm"; public static final String THEME_DEFAULT = "1"; // System public static final String SAVE_ATTACHMENT = "SaveAttachmentPreference"; public static final String CACHE_FOLDER = "CacheFolderPreference"; public static final String CACHE_FOLDER_MAX_SIZE = "CacheFolderMaxSizePreference"; public static final String CACHE_IMAGE_MAX_SIZE = "CacheImageMaxSizePreference"; public static final String CACHE_IMAGE_MIN_SIZE = "CacheImageMinSizePreference"; public static final String DELETE_DB_SCHEDULED = "DeleteDBScheduledPreference"; public static final String CACHE_IMAGES_ON_STARTUP = "CacheImagesOnStartupPreference"; public static final String CACHE_IMAGES_ONLY_WIFI = "CacheImagesOnlyWifiPreference"; public static final String ONLY_USE_WIFI = "OnlyUseWifiPreference"; public static final String NO_CRASHREPORTS = "NoCrashreportsPreference"; public static final String NO_CRASHREPORTS_UNTIL_UPDATE = "NoCrashreportsUntilUpdatePreference"; // System Default Values public static final String SAVE_ATTACHMENT_DEFAULT; public static final String CACHE_FOLDER_DEFAULT; public static final Integer CACHE_FOLDER_MAX_SIZE_DEFAULT = 80; public static final Integer CACHE_IMAGE_MAX_SIZE_DEFAULT = 6 * (int) Utils.MB; // 6 MB public static final Integer CACHE_IMAGE_MIN_SIZE_DEFAULT = 32 * (int) Utils.KB; // 64 KB public static final boolean DELETE_DB_SCHEDULED_DEFAULT = false; public static final boolean CACHE_IMAGES_ON_STARTUP_DEFAULT = false; public static final boolean CACHE_IMAGES_ONLY_WIFI_DEFAULT = false; public static final boolean ONLY_USE_WIFI_DEFAULT = false; public static final boolean NO_CRASHREPORTS_DEFAULT = false; public static final boolean NO_CRASHREPORTS_UNTIL_UPDATE_DEFAULT = false; // Internal public static final String API_LEVEL_UPDATED = "apiLevelUpdated"; public static final String API_LEVEL = "apiLevel"; public static final String APP_VERSION_CHECK_TIME = "appVersionCheckTime"; public static final String APP_LATEST_VERSION = "appLatestVersion"; public static final String LAST_UPDATE_TIME = "LastUpdateTime"; public static final String LAST_VERSION_RUN = "LastVersionRun"; public static final String FRESH_ARTICLE_MAX_AGE = "freshArticleMaxAge"; public static final String FRESH_ARTICLE_MAX_AGE_DATE = "freshArticleMaxAgeDate"; public static final String SINCE_ID = "sinceId"; public static final String LAST_SYNC = "lastSync"; public static final String LAST_CLEANUP = "lastCleanup"; // Internal Default Values public static final long API_LEVEL_UPDATED_DEFAULT = -1; public static final int API_LEVEL_DEFAULT = -1; public static final long APP_VERSION_CHECK_TIME_DEFAULT = 0; public static final int APP_LATEST_VERSION_DEFAULT = 0; public static final long LAST_UPDATE_TIME_DEFAULT = 1; public static final String LAST_VERSION_RUN_DEFAULT = "1"; public static final long FRESH_ARTICLE_MAX_AGE_DEFAULT = Utils.DAY; public static final long FRESH_ARTICLE_MAX_AGE_DATE_DEFAULT = 0; public static final int SINCE_ID_DEFAULT = 0; public static final long LAST_SYNC_DEFAULT = 0l; public static final long LAST_CLEANUP_DEFAULT = 0l; /* * Returns a list of the values of all constants in this class which represent preferences. Allows for easier * watching the changes in the preferences-activity. */ public static List<String> getConstants() { List<String> ret = new ArrayList<String>(); // Iterate over all fields for (Field field : Constants.class.getDeclaredFields()) { // Continue on "_DEFAULT"-Fields, these hold only the default values for a preference if (field.getName().endsWith(APPENDED_DEFAULT)) continue; try { // Return all String-Fields, these hold the preference-name if (field.get(null) instanceof String) { ret.add((String) field.get(null)); } } catch (Exception e) { e.printStackTrace(); } } return ret; } /* * Resets all preferences to their default values. Only preferences which are mentioned in this class are reset, old * or unsused values don't get reset. */ public static void resetPreferences(SharedPreferences prefs) { SharedPreferences.Editor editor = prefs.edit(); // Iterate over all fields for (Field field : Constants.class.getDeclaredFields()) { // Continue on "_DEFAULT"-Fields, these hold only the default values for a preference if (field.getName().endsWith(APPENDED_DEFAULT)) continue; try { // Get the default value Field fieldDefault = Constants.class.getDeclaredField(field.getName() + APPENDED_DEFAULT); String value = (String) field.get(new Constants()); // Get the default type and store value for the specific type String type = fieldDefault.getType().getSimpleName(); if (type.equals("String")) { String defaultValue = (String) fieldDefault.get(null); editor.putString(value, defaultValue); } else if (type.equals("boolean")) { boolean defaultValue = fieldDefault.getBoolean(null); editor.putBoolean(value, defaultValue); } else if (type.equals("int")) { int defaultValue = fieldDefault.getInt(null); editor.putInt(value, defaultValue); } else if (type.equals("long")) { long defaultValue = fieldDefault.getLong(null); editor.putLong(value, defaultValue); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { // Ignore, occurrs if a search for field like EMPTY_DEFAULT is started, this isn't there and shall never // be there. } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } // Commit when finished editor.commit(); } public static String constant2Var(String s) { String[] parts = s.split("_"); String camelCaseString = ""; for (String part : parts) { camelCaseString = camelCaseString + toProperCase(part); } // We want the String to starrt with a lower-case letter... return camelCaseString.substring(0, 1).toLowerCase(Locale.getDefault()) + camelCaseString.substring(1); } static String toProperCase(String s) { return s.substring(0, 1).toUpperCase(Locale.getDefault()) + s.substring(1).toLowerCase(Locale.getDefault()); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/preferences/Constants.java
Java
gpl3
14,219
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.model; import java.util.Date; import org.ttrssreader.R; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.utils.DateUtils; import android.content.Context; import android.database.Cursor; import android.graphics.Typeface; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class FeedHeadlineAdapter extends MainAdapter { protected static final String TAG = FeedHeadlineAdapter.class.getSimpleName(); private int feedId; private boolean selectArticlesForCategory; public FeedHeadlineAdapter(Context context, int feedId, boolean selectArticlesForCategory) { super(context); this.feedId = feedId; this.selectArticlesForCategory = selectArticlesForCategory; } @Override public Object getItem(int position) { Article ret = new Article(); Cursor cur = getCursor(); if (cur == null) return ret; if (cur.getCount() >= position) { if (cur.moveToPosition(position)) { ret.id = cur.getInt(0); ret.feedId = cur.getInt(1); ret.title = cur.getString(2); ret.isUnread = cur.getInt(3) != 0; ret.updated = new Date(cur.getLong(4)); ret.isStarred = cur.getInt(5) != 0; ret.isPublished = cur.getInt(6) != 0; } } return ret; } @SuppressWarnings("deprecation") private void getImage(ImageView icon, Article a) { if (a.isUnread) { icon.setBackgroundResource(R.drawable.articleunread48); } else { icon.setBackgroundResource(R.drawable.articleread48); } if (a.isStarred && a.isPublished) { icon.setImageResource(R.drawable.published_and_starred48); } else if (a.isStarred) { icon.setImageResource(R.drawable.star_yellow48); } else if (a.isPublished) { icon.setImageResource(R.drawable.published_blue48); } else { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { icon.setBackgroundDrawable(null); } else { icon.setBackground(null); } if (a.isUnread) { icon.setImageResource(R.drawable.articleunread48); } else { icon.setImageResource(R.drawable.articleread48); } } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position >= getCount() || position < 0) return new View(context); Article a = (Article) getItem(position); final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout layout = null; if (convertView == null) { layout = (LinearLayout) inflater.inflate(R.layout.item_feedheadline, parent, false); } else { if (convertView instanceof LinearLayout) { layout = (LinearLayout) convertView; } } if (layout == null) return new View(context); ImageView icon = (ImageView) layout.findViewById(R.id.icon); getImage(icon, a); TextView title = (TextView) layout.findViewById(R.id.title); title.setText(a.title); if (a.isUnread) title.setTypeface(Typeface.DEFAULT_BOLD); TextView updateDate = (TextView) layout.findViewById(R.id.updateDate); String date = DateUtils.getDateTime(context, a.updated); updateDate.setText(date.length() > 0 ? "(" + date + ")" : ""); TextView dataSource = (TextView) layout.findViewById(R.id.dataSource); // Display Feed-Title in Virtual-Categories or when displaying all Articles in a Category if ((feedId < 0 && feedId >= -4) || (selectArticlesForCategory)) { Feed f = DBHelper.getInstance().getFeed(a.feedId); if (f != null) { dataSource.setText(f.title); } } return layout; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/FeedHeadlineAdapter.java
Java
gpl3
5,031
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.model; import java.util.List; import org.ttrssreader.R; import android.content.Context; import android.preference.PreferenceActivity.Header; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; /** * <a href= * "http://stackoverflow.com/questions/15551673/android-headers-categories-in-preferenceactivity-with-preferencefragment" * >stackoverflow.com</a> */ public class HeaderAdapter extends ArrayAdapter<Header> { protected static final String TAG = HeaderAdapter.class.getSimpleName(); static final int HEADER_TYPE_CATEGORY = 0; static final int HEADER_TYPE_NORMAL = 1; private static final int HEADER_TYPE_COUNT = HEADER_TYPE_NORMAL + 1; private LayoutInflater mInflater; private static class HeaderViewHolder { ImageView icon; TextView title; TextView summary; } public HeaderAdapter(Context context, List<Header> objects) { super(context, 0, objects); mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } static int getHeaderType(Header header) { if (header.fragment == null && header.intent == null) return HEADER_TYPE_CATEGORY; else return HEADER_TYPE_NORMAL; } @Override public int getItemViewType(int position) { Header header = getItem(position); return getHeaderType(header); } @Override public boolean areAllItemsEnabled() { return false; /* because of categories */ } @Override public boolean isEnabled(int position) { return getItemViewType(position) != HEADER_TYPE_CATEGORY; } @Override public int getViewTypeCount() { return HEADER_TYPE_COUNT; } @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View convertView, ViewGroup parent) { HeaderViewHolder holder; Header header = getItem(position); int headerType = getHeaderType(header); View view = null; if (convertView == null) { holder = new HeaderViewHolder(); switch (headerType) { case HEADER_TYPE_CATEGORY: view = new TextView(getContext(), null, android.R.attr.listSeparatorTextViewStyle); holder.title = (TextView) view; break; case HEADER_TYPE_NORMAL: view = mInflater.inflate(R.layout.item_preferenceheader, parent, false); holder.icon = (ImageView) view.findViewById(R.id.ph_icon); holder.title = (TextView) view.findViewById(R.id.ph_title); holder.summary = (TextView) view.findViewById(R.id.ph_summary); break; } view.setTag(holder); } else { view = convertView; holder = (HeaderViewHolder) view.getTag(); } // All view fields must be updated every time, because the view may be recycled switch (headerType) { case HEADER_TYPE_CATEGORY: holder.title.setText(header.getTitle(getContext().getResources())); break; case HEADER_TYPE_NORMAL: holder.icon.setImageResource(header.iconRes); holder.title.setText(header.getTitle(getContext().getResources())); CharSequence summary = header.getSummary(getContext().getResources()); if (!TextUtils.isEmpty(summary)) { holder.summary.setVisibility(View.VISIBLE); holder.summary.setText(summary); } else { holder.summary.setVisibility(View.GONE); } break; } return view; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/HeaderAdapter.java
Java
gpl3
4,881
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.model; import java.util.ArrayList; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.controllers.Data; import org.ttrssreader.model.pojos.Category; import android.content.Context; import android.database.Cursor; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class CategoryAdapter extends MainAdapter { protected static final String TAG = CategoryAdapter.class.getSimpleName(); public CategoryAdapter(Context context) { super(context); } @Override public Object getItem(int position) { Category ret = new Category(); Cursor cur = getCursor(); if (cur == null) return ret; if (cur.getCount() >= position) { if (cur.moveToPosition(position)) { ret.id = cur.getInt(0); ret.title = cur.getString(1); ret.unread = cur.getInt(2); } } return ret; } public List<Category> getCategories() { List<Category> ret = new ArrayList<Category>(); Cursor cur = getCursor(); if (cur == null) return ret; if (cur.moveToFirst()) { while (!cur.isAfterLast()) { Category c = new Category(); c.id = cur.getInt(0); c.title = cur.getString(1); c.unread = cur.getInt(2); ret.add(c); cur.move(1); } } return ret; } private int getImage(int id, boolean unread) { if (id == Data.VCAT_STAR) { return R.drawable.star48; } else if (id == Data.VCAT_PUB) { return R.drawable.published48; } else if (id == Data.VCAT_FRESH) { return R.drawable.fresh48; } else if (id == Data.VCAT_ALL) { return R.drawable.all48; } else if (id < -10) { if (unread) { return R.drawable.label; } else { return R.drawable.label_read; } } else { if (unread) { return R.drawable.categoryunread48; } else { return R.drawable.categoryread48; } } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position >= getCount() || position < 0) return new View(context); Category c = (Category) getItem(position); final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout layout = null; if (convertView == null) { layout = (LinearLayout) inflater.inflate(R.layout.item_category, parent, false); } else { if (convertView instanceof LinearLayout) { layout = (LinearLayout) convertView; } } if (layout == null) return new View(context); ImageView icon = (ImageView) layout.findViewById(R.id.icon); icon.setImageResource(getImage(c.id, c.unread > 0)); TextView title = (TextView) layout.findViewById(R.id.title); title.setText(formatItemTitle(c.title, c.unread)); if (c.unread > 0) title.setTypeface(Typeface.DEFAULT_BOLD); return layout; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/CategoryAdapter.java
Java
gpl3
4,186
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.model; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.model.CategoryCursorHelper.MemoryDBOpenHelper; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class CustomCursorLoader extends CursorLoader { protected static final String TAG = CustomCursorLoader.class.getSimpleName(); TYPE type; int categoryId; int feedId; boolean selectArticlesForCategory; public CustomCursorLoader(Context context, TYPE type, int categoryId, int feedId, boolean selectArticlesForCategory) { super(context); this.type = type; this.categoryId = categoryId; this.feedId = feedId; this.selectArticlesForCategory = selectArticlesForCategory; } private final ForceLoadContentObserver mObserver = new ForceLoadContentObserver(); @Override public Cursor loadInBackground() { MainCursorHelper cursorHelper = null; SQLiteOpenHelper openHelper = new SQLiteOpenHelper(getContext(), DBHelper.DATABASE_NAME, null, DBHelper.DATABASE_VERSION) { @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { throw new RuntimeException("Upgrade not implemented here!"); } @Override public void onCreate(SQLiteDatabase db) { throw new RuntimeException("Create not implemented here!"); } }; SQLiteDatabase db = openHelper.getReadableDatabase(); switch (type) { case CATEGORY: { MemoryDBOpenHelper memoryDbOpenHelper = new MemoryDBOpenHelper(getContext()); SQLiteDatabase memoryDb = memoryDbOpenHelper.getWritableDatabase(); cursorHelper = new CategoryCursorHelper(getContext(), memoryDb); break; } case FEED: cursorHelper = new FeedCursorHelper(getContext(), categoryId); break; case FEEDHEADLINE: cursorHelper = new FeedHeadlineCursorHelper(getContext(), feedId, categoryId, selectArticlesForCategory); break; default: return null; } Cursor cursor = cursorHelper.makeQuery(db); if (cursor != null) { // Ensure the cursor window is filled cursor.getCount(); cursor.registerContentObserver(mObserver); } return cursor; } };
025003b-rss
ttrss-reader/src/org/ttrssreader/model/CustomCursorLoader.java
Java
gpl3
3,391
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.model; import org.ttrssreader.R; import org.ttrssreader.model.pojos.Feed; import android.content.Context; import android.database.Cursor; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class FeedAdapter extends MainAdapter { protected static final String TAG = FeedAdapter.class.getSimpleName(); public FeedAdapter(Context context) { super(context); } @Override public Object getItem(int position) { Feed ret = new Feed(); Cursor cur = getCursor(); if (cur == null) return ret; if (cur.getCount() >= position) { if (cur.moveToPosition(position)) { ret.id = cur.getInt(0); ret.title = cur.getString(1); ret.unread = cur.getInt(2); } } return ret; } private int getImage(boolean unread) { if (unread) { return R.drawable.feedheadlinesunread48; } else { return R.drawable.feedheadlinesread48; } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position >= getCount() || position < 0) return new View(context); Feed f = (Feed) getItem(position); final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout layout = null; if (convertView == null) { layout = (LinearLayout) inflater.inflate(R.layout.item_feed, parent, false); } else { if (convertView instanceof LinearLayout) { layout = (LinearLayout) convertView; } } if (layout == null) return new View(context); ImageView icon = (ImageView) layout.findViewById(R.id.icon); icon.setImageResource(getImage(f.unread > 0)); TextView title = (TextView) layout.findViewById(R.id.title); title.setText(formatItemTitle(f.title, f.unread)); if (f.unread > 0) title.setTypeface(Typeface.DEFAULT_BOLD); return layout; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/FeedAdapter.java
Java
gpl3
2,960
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.model; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.model.CategoryCursorHelper.MemoryDBOpenHelper; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; public class ListContentProvider extends ContentProvider { protected static final String TAG = ListContentProvider.class.getSimpleName(); private OpenHelper dbOpenHelper; private static final String AUTHORITY = "org.ttrssreader"; // Uri path segments private static final int CATS = 1; private static final int FEEDS = 2; private static final int HEADLINES = 3; // Params public static final String PARAM_CAT_ID = "categoryId"; public static final String PARAM_FEED_ID = "feedId"; public static final String PARAM_SELECT_FOR_CAT = "selectArticlesForCategory"; // Public information: private static final String BASE_PATH_CATEGORIES = "categories"; private static final String BASE_PATH_FEEDS = "feeds"; private static final String BASE_PATH_HEADLINES = "headlines"; public static final Uri CONTENT_URI_CAT = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_CATEGORIES); public static final Uri CONTENT_URI_FEED = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_FEEDS); public static final Uri CONTENT_URI_HEAD = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_HEADLINES); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/listitems"; public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/listitem"; private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { // Request all items: sURIMatcher.addURI(AUTHORITY, BASE_PATH_CATEGORIES, CATS); sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS, FEEDS); sURIMatcher.addURI(AUTHORITY, BASE_PATH_HEADLINES, HEADLINES); } @Override public boolean onCreate() { dbOpenHelper = new OpenHelper(getContext(), DBHelper.DATABASE_NAME, DBHelper.DATABASE_VERSION); return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Parse parameters: int categoryId = -1; int feedId = -1; boolean selectArticlesForCategory = false; String paramCat = uri.getQueryParameter(PARAM_CAT_ID); if (paramCat != null) categoryId = Integer.parseInt(paramCat); String paramFeedId = uri.getQueryParameter(PARAM_FEED_ID); if (paramFeedId != null) feedId = Integer.parseInt(paramFeedId); String paramSelectArticles = uri.getQueryParameter(PARAM_SELECT_FOR_CAT); if (paramSelectArticles != null) selectArticlesForCategory = ("1".equals(paramSelectArticles)); // Retrieve CursorHelper: MainCursorHelper cursorHelper = null; int uriType = sURIMatcher.match(uri); switch (uriType) { case CATS: { MemoryDBOpenHelper memoryDbOpenHelper = new MemoryDBOpenHelper(getContext()); SQLiteDatabase memoryDb = memoryDbOpenHelper.getWritableDatabase(); cursorHelper = new CategoryCursorHelper(getContext(), memoryDb); break; } case FEEDS: cursorHelper = new FeedCursorHelper(getContext(), categoryId); break; case HEADLINES: cursorHelper = new FeedHeadlineCursorHelper(getContext(), feedId, categoryId, selectArticlesForCategory); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); // Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); Cursor cursor = cursorHelper.makeQuery(db); // make sure that potential listeners are getting notified cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { throw new NoSuchMethodError(); // Not implemented! } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new NoSuchMethodError(); // Not implemented! } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new NoSuchMethodError(); // Not implemented! } class OpenHelper extends SQLiteOpenHelper { public OpenHelper(Context context, String databaseName, int databaseVersion) { super(context, databaseName, null, databaseVersion); } @Override public void onCreate(SQLiteDatabase database) { throw new NoSuchMethodError(); // Not implemented! } @Override public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { throw new NoSuchMethodError(); // Not implemented! } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/ListContentProvider.java
Java
gpl3
6,330
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.model.updaters; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.UpdateController; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; public class ReadStateUpdater implements IUpdatable { protected static final String TAG = ReadStateUpdater.class.getSimpleName(); private int state; private Collection<Category> categories = null; private Collection<Feed> feeds = null; private Collection<Article> articles = null; public static enum TYPE { ALL_CATEGORIES, ALL_FEEDS } public ReadStateUpdater(TYPE type) { this(type, -1); } public ReadStateUpdater(TYPE type, int id) { switch (type) { case ALL_CATEGORIES: categories = DBHelper.getInstance().getAllCategories(); break; case ALL_FEEDS: feeds = DBHelper.getInstance().getFeeds(id); break; } } public ReadStateUpdater(int categoryId) { categories = new HashSet<Category>(); Category ci = DBHelper.getInstance().getCategory(categoryId); if (ci != null) { categories.add(ci); } } public ReadStateUpdater(int feedId, int dummy) { if (feedId <= 0 && feedId >= -4) { // Virtual Category... categories = new HashSet<Category>(); Category ci = DBHelper.getInstance().getCategory(feedId); if (ci != null) categories.add(ci); } else { feeds = new HashSet<Feed>(); Feed fi = DBHelper.getInstance().getFeed(feedId); if (fi != null) feeds.add(fi); } } /* articleState: 0 = mark as read, 1 = mark as unread */ public ReadStateUpdater(Article article, int pid, int articleState) { articles = new ArrayList<Article>(); articles.add(article); state = articleState; article.isUnread = (articleState > 0); } /* articleState: 0 = mark as read, 1 = mark as unread */ public ReadStateUpdater(Collection<Article> articlesList, int pid, int articleState) { articles = new ArrayList<Article>(); articles.addAll(articlesList); state = articleState; for (Article article : articles) { article.isUnread = (articleState > 0); } } @Override public void update(Updater parent) { if (categories != null) { for (Category ci : categories) { // VirtualCats are actually Feeds (the server handles them as such) so we have to set isCat to false if (ci.id >= 0) { Data.getInstance().setRead(ci.id, true); } else { Data.getInstance().setRead(ci.id, false); } UpdateController.getInstance().notifyListeners(); } } else if (feeds != null) { for (Feed fi : feeds) { Data.getInstance().setRead(fi.id, false); UpdateController.getInstance().notifyListeners(); } } else if (articles != null) { Set<Integer> ids = new HashSet<Integer>(); for (Article article : articles) { ids.add(article.id); article.isUnread = (state > 0); } if (!ids.isEmpty()) { DBHelper.getInstance().markArticles(ids, "isUnread", state); UpdateController.getInstance().notifyListeners(); Data.getInstance().setArticleRead(ids, state); } } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/updaters/ReadStateUpdater.java
Java
gpl3
4,479
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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. */ package org.ttrssreader.model.updaters; import org.ttrssreader.controllers.Data; public class UnsubscribeUpdater implements IUpdatable { protected static final String TAG = UnsubscribeUpdater.class.getSimpleName(); private int feed_id; public UnsubscribeUpdater(int feed_id) { this.feed_id = feed_id; } @Override public void update(Updater parent) { Data.getInstance().feedUnsubscribe(feed_id); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/updaters/UnsubscribeUpdater.java
Java
gpl3
1,032