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 |
|---|---|---|---|---|---|
package com.ch_linghu.fanfoudroid.service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.FanfouWidget;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class WidgetService extends Service {
protected static final String TAG = "WidgetService";
private int position = 0;
private List<Tweet> tweets;
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId();
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
}else{
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews
.setTextViewText(R.id.status_text, tweets.get(position).text);
//updateViews.setOnClickPendingIntent(viewId, pendingIntent)
position++;
return updateViews;
}
private Handler handler = new Handler();
private Runnable mTask = new Runnable() {
@Override
public void run() {
Log.d(TAG, "tweets size="+tweets.size()+" position=" + position);
if (position >= tweets.size()) {
position = 0;
}
ComponentName fanfouWidget = new ComponentName(WidgetService.this,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager
.getInstance(getBaseContext());
manager.updateAppWidget(fanfouWidget,
buildUpdate(WidgetService.this));
handler.postDelayed(mTask, 10000);
}
};
public static void schedule(Context context) {
SharedPreferences preferences = TwitterApplication.mPref;
if (!preferences.getBoolean(Preferences.CHECK_UPDATES_KEY, false)) {
Log.d(TAG, "Check update preference is false.");
return;
}
String intervalPref = preferences
.getString(
Preferences.CHECK_UPDATE_INTERVAL_KEY,
context.getString(R.string.pref_check_updates_interval_default));
int interval = Integer.parseInt(intervalPref);
Intent intent = new Intent(context, WidgetService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, interval);
DateFormat df = new SimpleDateFormat("h:mm a");
Log.d(TAG, "Scheduling alarm at " + df.format(c.getTime()));
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending);
}
/**
* @see android.app.Service#onBind(Intent)
*/
@Override
public IBinder onBind(Intent intent) {
// TODO Put your code here
return null;
}
/**
* @see android.app.Service#onCreate()
*/
@Override
public void onCreate() {
Log.d(TAG, "WidgetService onCreate");
schedule(WidgetService.this);
}
/**
* @see android.app.Service#onStart(Intent,int)
*/
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "WidgetService onStart");
fetchMessages();
handler.removeCallbacks(mTask);
handler.postDelayed(mTask, 10000);
}
@Override
public void onDestroy() {
Log.d(TAG, "WidgetService Stop ");
handler.removeCallbacks(mTask);//当服务结束时,删除线程
super.onDestroy();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/service/WidgetService.java | Java | asf20 | 4,485 |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowersActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private static final String TAG = "FollowersActivity";
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWERS";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
private int followersCount=0;
private static final double PRE_PAGE_COUNT=100.0;//官方分页为每页100
private int pageCount=0;
private String[] ids;
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName=TwitterApplication.getMyselfName();
}
if (super._onCreate(savedInstanceState)) {
String myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_followers_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_followers_count_title), userName));
}
return true;
}else{
return false;
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFollowersList(userId, page);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/FollowersActivity.java | Java | asf20 | 2,576 |
/*
* Copyright (C) 2009 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.
*/
package com.ch_linghu.fanfoudroid;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.ImageCache;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class StatusActivity extends BaseActivity {
private static final String TAG = "StatusActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final String EXTRA_TWEET = "tweet";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.STATUS";
static final private int CONTEXT_REFRESH_ID = 0x0001;
static final private int CONTEXT_CLIPBOARD_ID = 0x0002;
static final private int CONTEXT_DELETE_ID = 0x0003;
// Task TODO: tasks
private GenericTask mReplyTask;
private GenericTask mStatusTask;
private GenericTask mPhotoTask; // TODO: 压缩图片,提供获取图片的过程中可取消获取
private GenericTask mFavTask;
private GenericTask mDeleteTask;
private NavBar mNavbar;
private Feedback mFeedback;
private TaskListener mReplyTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
showReplyStatus(replyTweet);
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
return "GetReply";
}
};
private TaskListener mStatusTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
clean();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
StatusActivity.this.mFeedback.success("");
draw();
}
@Override
public String getName() {
return "GetStatus";
}
};
private TaskListener mPhotoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
status_photo.setImageBitmap(mPhotoBitmap);
} else {
status_photo.setVisibility(View.GONE);
}
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "GetPhoto";
}
};
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "DeleteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onDeleteSuccess();
} else if (result == TaskResult.IO_ERROR) {
onDeleteFailure();
}
}
};
// View
private TextView tweet_screen_name;
private TextView tweet_text;
private TextView tweet_user_info;
private ImageView profile_image;
private TextView tweet_source;
private TextView tweet_created_at;
private ImageButton btn_person_more;
private ImageView status_photo = null; // if exists
private ViewGroup reply_wrap;
private TextView reply_status_text = null; // if exists
private TextView reply_status_date = null; // if exists
private ImageButton tweet_fav;
private Tweet tweet = null;
private Tweet replyTweet = null; // if exists
private HttpClient mClient;
private Bitmap mPhotoBitmap = ImageCache.mDefaultBitmap; // if exists
public static Intent createIntent(Tweet tweet) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_TWEET, tweet);
return intent;
}
private static Pattern PHOTO_PAGE_LINK = Pattern
.compile("http://fanfou.com(/photo/[-a-zA-Z0-9+&@#%?=~_|!:,.;]*[-a-zA-Z0-9+&@#%=~_|])");
private static Pattern PHOTO_SRC_LINK = Pattern
.compile("src=\"(http:\\/\\/photo\\.fanfou\\.com\\/.*?)\"");
/**
* 获得消息中的照片页面链接
*
* @param text
* 消息文本
* @param size
* 照片尺寸
* @return 照片页面的链接,若不存在,则返回null
*/
public static String getPhotoPageLink(String text, String size) {
Matcher m = PHOTO_PAGE_LINK.matcher(text);
if (m.find()) {
String THUMBNAIL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_thumbnail);
String MIDDLE = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_middle);
String ORIGINAL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_original);
if (size.equals(THUMBNAIL) || size.equals(MIDDLE)) {
return "http://m.fanfou.com" + m.group(1);
} else if (size.endsWith(ORIGINAL)) {
return m.group(0);
} else {
return null;
}
} else {
return null;
}
}
/**
* 获得照片页面中的照片链接
*
* @param pageHtml
* 照片页面文本
* @return 照片链接,若不存在,则返回null
*/
public static String getPhotoURL(String pageHtml) {
Matcher m = PHOTO_SRC_LINK.matcher(pageHtml);
if (m.find()) {
return m.group(1);
} else {
return null;
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
mClient = getApi().getHttpClient();
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
Bundle extras = intent.getExtras();
// Must has extras
if (null == extras) {
Log.e(TAG, this.getClass().getName() + " must has extras.");
finish();
return false;
}
setContentView(R.layout.status);
mNavbar = new NavBar(NavBar.HEADER_STYLE_BACK, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
findView();
bindNavBarListener();
// Set view with intent data
this.tweet = extras.getParcelable(EXTRA_TWEET);
draw();
bindFooterBarListener();
bindReplyViewListener();
return true;
} else {
return false;
}
}
private void findView() {
tweet_screen_name = (TextView) findViewById(R.id.tweet_screen_name);
tweet_user_info = (TextView) findViewById(R.id.tweet_user_info);
tweet_text = (TextView) findViewById(R.id.tweet_text);
tweet_source = (TextView) findViewById(R.id.tweet_source);
profile_image = (ImageView) findViewById(R.id.profile_image);
tweet_created_at = (TextView) findViewById(R.id.tweet_created_at);
btn_person_more = (ImageButton) findViewById(R.id.person_more);
tweet_fav = (ImageButton) findViewById(R.id.tweet_fav);
reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
status_photo = (ImageView) findViewById(R.id.status_photo);
}
private void bindNavBarListener() {
mNavbar.getRefreshButton().setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetStatus(tweet.id);
}
});
}
private void bindFooterBarListener() {
// person_more
btn_person_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = ProfileActivity.createIntent(tweet.userId);
startActivity(intent);
}
});
// Footer bar
TextView footer_btn_share = (TextView) findViewById(R.id.footer_btn_share);
TextView footer_btn_reply = (TextView) findViewById(R.id.footer_btn_reply);
TextView footer_btn_retweet = (TextView) findViewById(R.id.footer_btn_retweet);
TextView footer_btn_fav = (TextView) findViewById(R.id.footer_btn_fav);
TextView footer_btn_more = (TextView) findViewById(R.id.footer_btn_more);
// 分享
footer_btn_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(
Intent.EXTRA_TEXT,
String.format("@%s %s", tweet.screenName,
TextHelper.getSimpleTweetText(tweet.text)));
startActivity(Intent.createChooser(intent,
getString(R.string.cmenu_share)));
}
});
// 回复
footer_btn_reply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewReplyIntent(
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
}
});
// 转发
footer_btn_retweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewRepostIntent(
StatusActivity.this, tweet.text, tweet.screenName,
tweet.id);
startActivity(intent);
}
});
// 收藏/取消收藏
footer_btn_fav.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tweet.favorited.equals("true")) {
doFavorite("del", tweet.id);
} else {
doFavorite("add", tweet.id);
}
}
});
// TODO: 更多操作
registerForContextMenu(footer_btn_more);
footer_btn_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
private void bindReplyViewListener() {
// 点击回复消息打开新的Status界面
OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
if (replyTweet == null) {
Log.w(TAG, "Selected item not available.");
} else {
launchActivity(StatusActivity.createIntent(replyTweet));
}
}
}
};
reply_wrap.setOnClickListener(listener);
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
mReplyTask.cancel(true);
}
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
mPhotoTask.cancel(true);
}
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
super.onDestroy();
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profile_image.setImageBitmap(bitmap);
}
};
private void clean() {
tweet_screen_name.setText("");
tweet_text.setText("");
tweet_created_at.setText("");
tweet_source.setText("");
tweet_user_info.setText("");
tweet_fav.setEnabled(false);
profile_image.setImageBitmap(ImageCache.mDefaultBitmap);
status_photo.setVisibility(View.GONE);
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.GONE);
}
private void draw() {
Log.d(TAG, "draw");
String PHOTO_PREVIEW_TYPE_NONE = getString(R.string.pref_photo_preview_type_none);
String PHOTO_PREVIEW_TYPE_THUMBNAIL = getString(R.string.pref_photo_preview_type_thumbnail);
String PHOTO_PREVIEW_TYPE_MIDDLE = getString(R.string.pref_photo_preview_type_middle);
String PHOTO_PREVIEW_TYPE_ORIGINAL = getString(R.string.pref_photo_preview_type_original);
SharedPreferences pref = getPreferences();
String photoPreviewSize = pref.getString(Preferences.PHOTO_PREVIEW,
PHOTO_PREVIEW_TYPE_ORIGINAL);
boolean forceShowAllImage = pref.getBoolean(
Preferences.FORCE_SHOW_ALL_IMAGE, false);
tweet_screen_name.setText(tweet.screenName);
TextHelper.setTweetText(tweet_text, tweet.text);
tweet_created_at.setText(DateTimeHelper.getRelativeDate(tweet.createdAt));
tweet_source.setText(getString(R.string.tweet_source_prefix)
+ tweet.source);
tweet_user_info.setText(tweet.userId);
boolean isFav = (tweet.favorited.equals("true")) ? true : false;
tweet_fav.setEnabled(isFav);
// Bitmap mProfileBitmap =
// TwitterApplication.mImageManager.get(tweet.profileImageUrl);
profile_image
.setImageBitmap(TwitterApplication.mImageLoader
.get(tweet.profileImageUrl, callback));
// has photo
if (!photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_NONE)) {
String photoLink;
boolean isPageLink = false;
if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_THUMBNAIL)) {
photoLink = tweet.thumbnail_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_MIDDLE)) {
photoLink = tweet.bmiddle_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_ORIGINAL)) {
photoLink = tweet.original_pic;
} else {
Log.e(TAG, "Invalid Photo Preview Size Type");
photoLink = "";
}
// 如果选用了强制显示则再尝试分析图片链接
if (forceShowAllImage) {
photoLink = getPhotoPageLink(tweet.text, photoPreviewSize);
isPageLink = true;
}
if (!TextUtils.isEmpty(photoLink)) {
status_photo.setVisibility(View.VISIBLE);
status_photo.setImageBitmap(mPhotoBitmap);
doGetPhoto(photoLink, isPageLink);
}
} else {
status_photo.setVisibility(View.GONE);
}
// has reply
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.VISIBLE);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
doGetReply(tweet.inReplyToStatusId);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
private String fetchWebPage(String url) throws HttpException {
Log.d(TAG, "Fetching WebPage: " + url);
Response res = mClient.get(url);
return res.asString();
}
private Bitmap fetchPhotoBitmap(String url) throws HttpException,
IOException {
Log.d(TAG, "Fetching Photo: " + url);
Response res = mClient.get(url);
//FIXME:这里使用了一个作废的方法,如何修正?
InputStream is = res.asStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
private void doGetReply(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mReplyTask = new GetReplyTask();
mReplyTask.setListener(mReplyTaskListener);
TaskParams params = new TaskParams();
params.put("reply_id", status_id);
mReplyTask.execute(params);
}
}
private class GetReplyTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String reply_id = param.getString("reply_id");
if (!TextUtils.isEmpty(reply_id)) {
// 首先查看是否在数据库中,如不在再去获取
replyTweet = getDb().queryTweet(reply_id, -1);
if (replyTweet == null) {
status = getApi().showStatus(reply_id);
replyTweet = Tweet.create(status);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void doGetStatus(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mStatusTask != null
&& mStatusTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mStatusTask = new GetStatusTask();
mStatusTask.setListener(mStatusTaskListener);
TaskParams params = new TaskParams();
params.put("id", status_id);
mStatusTask.execute(params);
}
}
private class GetStatusTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String id = param.getString("id");
if (!TextUtils.isEmpty(id)) {
status = getApi().showStatus(id);
mFeedback.update(80);
tweet = Tweet.create(status);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
private void doGetPhoto(String photoPageURL, boolean isPageLink) {
mFeedback.start("");
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mPhotoTask = new GetPhotoTask();
mPhotoTask.setListener(mPhotoTaskListener);
TaskParams params = new TaskParams();
params.put("photo_url", photoPageURL);
params.put("is_page_link", isPageLink);
mPhotoTask.execute(params);
}
}
private class GetPhotoTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String photoURL = param.getString("photo_url");
boolean isPageLink = param.getBoolean("is_page_link");
if (!TextUtils.isEmpty(photoURL)) {
if (isPageLink) {
String pageHtml = fetchWebPage(photoURL);
String photoSrcURL = getPhotoURL(pageHtml);
if (photoSrcURL != null) {
mPhotoBitmap = fetchPhotoBitmap(photoSrcURL);
}
} else {
mPhotoBitmap = fetchPhotoBitmap(photoURL);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void showReplyStatus(Tweet tweet) {
if (tweet != null) {
String text = tweet.screenName + " : " + tweet.text;
TextHelper.setSimpleTweetText(reply_status_text, text);
reply_status_date.setText(DateTimeHelper.getRelativeDate(tweet.createdAt));
} else {
String msg = MessageFormat.format(
getString(R.string.status_status_reply_cannot_display),
this.tweet.inReplyToScreenName);
reply_status_text.setText(msg);
}
}
public void onDeleteFailure() {
Log.e(TAG, "Delete failed");
}
public void onDeleteSuccess() {
finish();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
if (!TextUtils.isEmpty(id)) {
Log.d(TAG, "doFavorite.");
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams param = new TaskParams();
param.put("action", action);
param.put("id", id);
mFavTask.execute(param);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
if (((TweetCommonTask.FavoriteTask) mFavTask).getType().equals(
TweetCommonTask.FavoriteTask.TYPE_ADD)) {
tweet.favorited = "true";
tweet_fav.setEnabled(true);
} else {
tweet.favorited = "false";
tweet_fav.setEnabled(false);
}
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
private void doDelete(String id) {
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new TweetCommonTask.DeleteTask(this);
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_REFRESH_ID:
doGetStatus(tweet.id);
return true;
case CONTEXT_CLIPBOARD_ID:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(TextHelper.getSimpleTweetText(tweet.text));
return true;
case CONTEXT_DELETE_ID:
doDelete(tweet.id);
return true;
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderIcon(android.R.drawable.ic_menu_more);
menu.setHeaderTitle(getString(R.string.cmenu_more));
menu.add(0, CONTEXT_REFRESH_ID, 0, R.string.omenu_refresh);
menu.add(0, CONTEXT_CLIPBOARD_ID, 0, R.string.cmenu_clipboard);
if (tweet.userId.equals(TwitterApplication.getMyselfId())) {
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/StatusActivity.java | Java | asf20 | 23,343 |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.fanfou.SavedSearch;
import com.ch_linghu.fanfoudroid.fanfou.Trend;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.TextHelper;
import com.commonsware.cwac.merge.MergeAdapter;
public class SearchActivity extends BaseActivity {
private static final String TAG = SearchActivity.class.getSimpleName();
private static final int LOADING = 1;
private static final int NETWORKERROR = 2;
private static final int SUCCESS = 3;
private EditText mSearchEdit;
private ListView mSearchSectionList;
private TextView trendsTitle;
private TextView savedSearchTitle;
private MergeAdapter mSearchSectionAdapter;
private SearchAdapter trendsAdapter;
private SearchAdapter savedSearchesAdapter;
private ArrayList<SearchItem> trends;
private ArrayList<SearchItem> savedSearch;
private String initialQuery;
private NavBar mNavbar;
private Feedback mFeedback;
private GenericTask trendsAndSavedSearchesTask;
private TaskListener trendsAndSavedSearchesTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "trendsAndSavedSearchesTask";
}
@Override
public void onPreExecute(GenericTask task) {
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
refreshSearchSectionList(SearchActivity.SUCCESS);
} else if (result == TaskResult.IO_ERROR) {
refreshSearchSectionList(SearchActivity.NETWORKERROR);
Toast.makeText(
SearchActivity.this,
getResources()
.getString(
R.string.login_status_network_or_connection_error),
Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()...");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.search);
mNavbar = new NavBar(NavBar.HEADER_STYLE_SEARCH, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
initView();
initSearchSectionList();
refreshSearchSectionList(SearchActivity.LOADING);
doGetSavedSearches();
return true;
} else {
return false;
}
}
private void initView() {
mSearchEdit = (EditText) findViewById(R.id.search_edit);
mSearchEdit.setOnKeyListener(enterKeyHandler);
trendsTitle = (TextView) getLayoutInflater().inflate(
R.layout.search_section_header, null);
trendsTitle.setText(getResources().getString(R.string.trends_title));
savedSearchTitle = (TextView) getLayoutInflater().inflate(
R.layout.search_section_header, null);
savedSearchTitle.setText(getResources().getString(
R.string.saved_search_title));
mSearchSectionAdapter = new MergeAdapter();
mSearchSectionList = (ListView) findViewById(R.id.search_section_list);
mNavbar.getSearchButton().setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
initialQuery = mSearchEdit.getText().toString();
startSearch();
}
});
}
@Override
protected void onResume() {
Log.d(TAG, "onResume()...");
super.onResume();
}
private void doGetSavedSearches() {
if (trendsAndSavedSearchesTask != null
&& trendsAndSavedSearchesTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
trendsAndSavedSearchesTask = new TrendsAndSavedSearchesTask();
trendsAndSavedSearchesTask
.setListener(trendsAndSavedSearchesTaskListener);
trendsAndSavedSearchesTask.setFeedback(mFeedback);
trendsAndSavedSearchesTask.execute();
}
}
private void initSearchSectionList() {
trends = new ArrayList<SearchItem>();
savedSearch = new ArrayList<SearchItem>();
trendsAdapter = new SearchAdapter(this);
savedSearchesAdapter = new SearchAdapter(this);
mSearchSectionAdapter.addView(savedSearchTitle);
mSearchSectionAdapter.addAdapter(savedSearchesAdapter);
mSearchSectionAdapter.addView(trendsTitle);
mSearchSectionAdapter.addAdapter(trendsAdapter);
mSearchSectionList.setAdapter(mSearchSectionAdapter);
}
/**
* 辅助计算位置的类
*
* @author jmx
*
*/
class PositionHelper {
/**
* 返回指定位置属于哪一个小节
*
* @param position
* 绝对位置
* @return 小节的序号,0是第一小节,1是第二小节, -1为无效位置
*/
public int getSectionIndex(int position) {
int[] contentLength = new int[2];
contentLength[0] = savedSearchesAdapter.getCount();
contentLength[1] = trendsAdapter.getCount();
if (position > 0 && position < contentLength[0] + 1) {
return 0;
} else if (position > contentLength[0] + 1
&& position < (contentLength[0] + contentLength[1] + 1) + 1) {
return 1;
} else {
return -1;
}
}
/**
* 返回指定位置在自己所在小节的相对位置
*
* @param position
* 绝对位置
* @return 所在小节的相对位置,-1为无效位置
*/
public int getRelativePostion(int position) {
int[] contentLength = new int[2];
contentLength[0] = savedSearchesAdapter.getCount();
contentLength[1] = trendsAdapter.getCount();
int sectionIndex = getSectionIndex(position);
int offset = 0;
for (int i = 0; i < sectionIndex; ++i) {
offset += contentLength[i] + 1;
}
return position - offset - 1;
}
}
/**
* flag: loading;network error;success
*/
PositionHelper pos_helper = new PositionHelper();
private void refreshSearchSectionList(int flag) {
AdapterView.OnItemClickListener searchSectionListListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
MergeAdapter adapter = (MergeAdapter) (adapterView.getAdapter());
SearchAdapter subAdapter = (SearchAdapter) adapter
.getAdapter(position);
// 计算针对subAdapter中的相对位置
int relativePos = pos_helper.getRelativePostion(position);
SearchItem item = (SearchItem) (subAdapter.getItem(relativePos));
initialQuery = item.query;
startSearch();
}
};
if (flag == SearchActivity.LOADING) {
mSearchSectionList.setOnItemClickListener(null);
savedSearch.clear();
trends.clear();
savedSearchesAdapter.refresh(getString(R.string.search_loading));
trendsAdapter.refresh(getString(R.string.search_loading));
} else if (flag == SearchActivity.NETWORKERROR) {
mSearchSectionList.setOnItemClickListener(null);
savedSearch.clear();
trends.clear();
savedSearchesAdapter
.refresh(getString(R.string.login_status_network_or_connection_error));
trendsAdapter
.refresh(getString(R.string.login_status_network_or_connection_error));
} else {
savedSearchesAdapter.refresh(savedSearch);
trendsAdapter.refresh(trends);
}
if (flag == SearchActivity.SUCCESS) {
mSearchSectionList
.setOnItemClickListener(searchSectionListListener);
}
}
protected boolean startSearch() {
if (!TextUtils.isEmpty(initialQuery)) {
// 以下这个方法在7可用,在8就报空指针
// triggerSearch(initialQuery, null);
Intent i = new Intent(this, SearchResultActivity.class);
i.putExtra(SearchManager.QUERY, initialQuery);
startActivity(i);
} else if (TextUtils.isEmpty(initialQuery)) {
Toast.makeText(this,
getResources().getString(R.string.search_box_null),
Toast.LENGTH_SHORT).show();
return false;
}
return false;
}
// 搜索框回车键判断
private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
initialQuery = mSearchEdit.getText().toString();
startSearch();
}
return true;
}
return false;
}
};
private class TrendsAndSavedSearchesTask extends GenericTask {
Trend[] trendsList;
List<SavedSearch> savedSearchsList;
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
trendsList = getApi().getTrends().getTrends();
savedSearchsList = getApi().getSavedSearches();
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
trends.clear();
savedSearch.clear();
for (int i = 0; i < trendsList.length; i++) {
SearchItem item = new SearchItem();
item.name = trendsList[i].getName();
item.query = trendsList[i].getQuery();
trends.add(item);
}
for (int i = 0; i < savedSearchsList.size(); i++) {
SearchItem item = new SearchItem();
item.name = savedSearchsList.get(i).getName();
item.query = savedSearchsList.get(i).getQuery();
savedSearch.add(item);
}
return TaskResult.OK;
}
}
}
class SearchItem {
public String name;
public String query;
}
class SearchAdapter extends BaseAdapter {
protected ArrayList<SearchItem> mSearchList;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
public SearchAdapter(Context context) {
mSearchList = new ArrayList<SearchItem>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
public SearchAdapter(Context context, String prompt) {
this(context);
refresh(prompt);
}
public void refresh(ArrayList<SearchItem> searchList) {
mSearchList = searchList;
notifyDataSetChanged();
}
public void refresh(String prompt) {
SearchItem item = new SearchItem();
item.name = prompt;
item.query = null;
mSearchList.clear();
mSearchList.add(item);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mSearchList.size();
}
@Override
public Object getItem(int position) {
return mSearchList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(R.layout.search_section_view, parent,
false);
TextView text = (TextView) view
.findViewById(R.id.search_section_text);
view.setTag(text);
} else {
view = convertView;
}
TextView text = (TextView) view.getTag();
SearchItem item = mSearchList.get(position);
text.setText(item.name);
return view;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/SearchActivity.java | Java | asf20 | 13,735 |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Query;
import com.ch_linghu.fanfoudroid.fanfou.QueryResult;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.MyListView;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
public class SearchResultActivity extends TwitterListBaseActivity implements
MyListView.OnNeedMoreListener {
private static final String TAG = "SearchActivity";
// Views.
private MyListView mTweetList;
// State.
private String mSearchQuery;
private ArrayList<Tweet> mTweets;
private TweetArrayAdapter mAdapter;
private int mNextPage = 1;
private String mLastId = null;
private static class State {
State(SearchResultActivity activity) {
mTweets = activity.mTweets;
mNextPage = activity.mNextPage;
}
public ArrayList<Tweet> mTweets;
public int mNextPage;
}
// Tasks.
private GenericTask mSearchTask;
private TaskListener mSearchTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
if (mNextPage == 1) {
updateProgress(getString(R.string.page_status_refreshing));
} else {
updateProgress(getString(R.string.page_status_refreshing));
}
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
draw();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "SearchTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
Intent intent = getIntent();
// Assume it's SEARCH.
// String action = intent.getAction();
mSearchQuery = intent.getStringExtra(SearchManager.QUERY);
if (TextUtils.isEmpty(mSearchQuery)) {
mSearchQuery = intent.getData().getLastPathSegment();
}
mNavbar.setHeaderTitle(mSearchQuery);
setTitle(mSearchQuery);
State state = (State) getLastNonConfigurationInstance();
if (state != null) {
mTweets = state.mTweets;
draw();
} else {
doSearch();
}
return true;
}else{
return false;
}
}
@Override
protected int getLayoutId(){
return R.layout.main;
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
public Object onRetainNonConfigurationInstance() {
return createState();
}
private synchronized State createState() {
return new State(this);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSearchTask != null
&& mSearchTask.getStatus() == GenericTask.Status.RUNNING) {
mSearchTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
private void doSearch() {
Log.d(TAG, "Attempting search.");
if (mSearchTask != null && mSearchTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mSearchTask = new SearchTask();
mSearchTask.setFeedback(mFeedback);
mSearchTask.setListener(mSearchTaskListener);
mSearchTask.execute();
}
}
private class SearchTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams...params) {
QueryResult result;
try {
Query query = new Query(mSearchQuery);
if (!TextUtils.isEmpty(mLastId)){
query.setMaxId(mLastId);
}
result = getApi().search(query);//.search(mSearchQuery, mNextPage);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
List<com.ch_linghu.fanfoudroid.fanfou.Status> statuses = result.getStatus();
HashSet<String> imageUrls = new HashSet<String>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, statuses));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statuses) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mLastId = tweet.id;
mTweets.add(tweet);
imageUrls.add(tweet.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress();
//
// // TODO: what if orientation change?
// ImageManager imageManager = getImageManager();
// MemoryImageCache imageCache = new MemoryImageCache();
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// Bitmap bitmap = imageManager.fetchImage(imageUrl);
// imageCache.put(imageUrl, bitmap);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
//
// addImages(imageCache);
return TaskResult.OK;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public void needMore() {
if (!isLastPage()) {
doSearch();
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
@Override
protected void adapterRefresh() {
mAdapter.refresh(mTweets);
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return mSearchQuery;
}
@Override
protected Tweet getContextItemTweet(int position) {
return (Tweet)mAdapter.getItem(position);
}
@Override
protected TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO Simple and stupid implementation
for (Tweet t : mTweets){
if (t.id.equals(tweet.id)){
t.favorited = tweet.favorited;
break;
}
}
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mTweetList = (MyListView) findViewById(R.id.tweet_list);
mAdapter = new TweetArrayAdapter(this);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnNeedMoreListener(this);
}
@Override
public void doRetrieve() {
doSearch();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/SearchResultActivity.java | Java | asf20 | 7,831 |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
public final class UserInfoTable implements BaseColumns {
public static final String TAG = "UserInfoTable";
public static final String TABLE_NAME = "userinfo";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String FIELD_FOLLOWER_IDS="follower_ids";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME,
FIELD_LOCALTION, FIELD_DESCRIPTION,
FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED,
FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT,
FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING};
public static final String CREATE_TABLE = "create table "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, "
+ FIELD_USER_SCREEN_NAME + " text, "
+ FIELD_LOCALTION + " text, "
+ FIELD_DESCRIPTION + " text, "
+ FIELD_PROFILE_IMAGE_URL + " text, "
+ FIELD_URL + " text, "
+ FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, "
+ FIELD_FRIENDS_COUNT + " integer, "
+ FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, "
+ FIELD_LAST_STATUS + " text, "
+ FIELD_CREATED_AT + " date, "
+ FIELD_FOLLOWING + " boolean "
//+FIELD_FOLLOWER_IDS+" text"
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(_ID));
user.name = cursor.getString(cursor.getColumnIndex(FIELD_USER_NAME));
user.screenName = cursor.getString(cursor.getColumnIndex(FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor.getColumnIndex(FIELD_LOCALTION));
user.description = cursor.getString(cursor.getColumnIndex(FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor.getColumnIndex(FIELD_LAST_STATUS));
user.friendsCount = cursor.getInt(cursor.getColumnIndex(FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor.getColumnIndex(FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWING))) ? false : true;
//TODO:报空指针异常,待查
// try {
// user.createdAt = StatusDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
// } catch (ParseException e) {
// Log.w(TAG, "Invalid created at data.");
// }
return user;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db/UserInfoTable.java | Java | asf20 | 4,443 |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
/**
* Table - Followers
*
*/
public final class FollowTable implements BaseColumns {
public static final String TAG = "FollowTable";
public static final String TABLE_NAME = "followers";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME,
FIELD_LOCALTION, FIELD_DESCRIPTION,
FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED,
FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT,
FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING};
public static final String CREATE_TABLE = "create table "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, "
+ FIELD_USER_SCREEN_NAME + " text, "
+ FIELD_LOCALTION + " text, "
+ FIELD_DESCRIPTION + " text, "
+ FIELD_PROFILE_IMAGE_URL + " text, "
+ FIELD_URL + " text, "
+ FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, "
+ FIELD_FRIENDS_COUNT + " integer, "
+ FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, "
+ FIELD_LAST_STATUS + " text, "
+ FIELD_CREATED_AT + " date, "
+ FIELD_FOLLOWING + " boolean "
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(FollowTable._ID));
user.name = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_NAME));
user.screenName = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LOCALTION));
user.description = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LAST_STATUS));;
user.friendsCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWING))) ? false : true;
try {
user.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
return user;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db/FollowTable.java | Java | asf20 | 4,626 |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* Table - Statuses
* <br /> <br />
* 为节省流量,故此表不保证本地数据库中所有消息具有前后连贯性, 而只确保最新的MAX_ROW_NUM条<br />
* 数据的连贯性, 超出部分则视为垃圾数据, 不再允许读取, 也不保证其是前后连续的.<br />
* <br />
* 因为用户可能中途长时间停止使用本客户端,而换其他客户端(如网页), <br />
* 如果保证本地所有数据的连贯性, 那么就必须自动去下载所有本地缺失的中间数据,<br />
* 而这些数据极有可能是用户通过其他客户端阅读过的无用信息, 浪费了用户流量.<br />
* <br />
* 即认为相对于旧信息而言, 新信息对于用户更为价值, 所以只会新信息进行维护, <br />
* 而旧信息一律视为无用的, 如用户需要查看超过MAX_ROW_NUM的旧数据, 可主动点击, <br />
* 从而请求服务器. 本地只缓存最有价值的MAX条最新信息.<br />
* <br />
* 本地数据库中前MAX_ROW_NUM条的数据模拟一个定长列队, 即在尾部插入N条消息, 就会使得头部<br />
* 的N条消息被标记为垃圾数据(但并不立即收回),只有在认为数据库数据过多时,<br />
* 可手动调用 <code>StatusDatabase.gc(int type)</code> 方法进行垃圾清理.<br />
*
*
*/
public final class StatusTable implements BaseColumns {
public static final String TAG = "StatusTable";
// Status Types
public static final int TYPE_HOME = 1; //首页(我和我的好友)
public static final int TYPE_MENTION = 2; //提到我的
public static final int TYPE_USER = 3; //指定USER的
public static final int TYPE_FAVORITE = 4; //收藏
public static final int TYPE_BROWSE = 5; //随便看看
public static final String TABLE_NAME = "status";
public static final int MAX_ROW_NUM = 20; //单类型数据安全区域
public static final String OWNER_ID = "owner"; //用于标识数据的所有者。以便于处理其他用户的信息(如其他用户的收藏)
public static final String USER_ID = "uid";
public static final String USER_SCREEN_NAME = "screen_name";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String CREATED_AT = "created_at";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String TRUNCATED = "truncated";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FAVORITED = "favorited";
public static final String IS_UNREAD = "is_unread";
public static final String STATUS_TYPE = "status_type";
public static final String PIC_THUMB = "pic_thumbnail";
public static final String PIC_MID = "pic_middle";
public static final String PIC_ORIG = "pic_original";
// private static final String FIELD_PHOTO_URL = "photo_url";
// private double latitude = -1;
// private double longitude = -1;
// private String thumbnail_pic;
// private String bmiddle_pic;
// private String original_pic;
public static final String[] TABLE_COLUMNS = new String[] {_ID, USER_SCREEN_NAME,
TEXT, PROFILE_IMAGE_URL, IS_UNREAD, CREATED_AT,
FAVORITED, IN_REPLY_TO_STATUS_ID, IN_REPLY_TO_USER_ID,
IN_REPLY_TO_SCREEN_NAME, TRUNCATED,
PIC_THUMB, PIC_MID, PIC_ORIG,
SOURCE, USER_ID, STATUS_TYPE, OWNER_ID};
public static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + " ("
+ _ID + " text not null,"
+ STATUS_TYPE + " text not null, "
+ OWNER_ID + " text not null, "
+ USER_ID + " text not null, "
+ USER_SCREEN_NAME + " text not null, "
+ TEXT + " text not null, "
+ PROFILE_IMAGE_URL + " text not null, "
+ IS_UNREAD + " boolean not null, "
+ CREATED_AT + " date not null, "
+ SOURCE + " text not null, "
+ FAVORITED + " text, " // TODO : text -> boolean
+ IN_REPLY_TO_STATUS_ID + " text, "
+ IN_REPLY_TO_USER_ID + " text, "
+ IN_REPLY_TO_SCREEN_NAME + " text, "
+ PIC_THUMB + " text, "
+ PIC_MID + " text, "
+ PIC_ORIG + " text, "
+ TRUNCATED + " boolean ,"
+ "PRIMARY KEY (" + _ID + ","+ OWNER_ID + "," + STATUS_TYPE + "))";
/**
* 将游标解析为一条Tweet
*
*
* @param cursor 该方法不会移动或关闭游标
* @return 成功返回 Tweet 类型的单条数据, 失败返回null
*/
public static Tweet parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
} else if ( -1 == cursor.getPosition() ) {
cursor.moveToFirst();
}
Tweet tweet = new Tweet();
tweet.id = cursor.getString(cursor.getColumnIndex(_ID));
tweet.createdAt = DateTimeHelper.parseDateTimeFromSqlite(cursor.getString(cursor.getColumnIndex(CREATED_AT)));
tweet.favorited = cursor.getString(cursor.getColumnIndex(FAVORITED));
tweet.screenName = cursor.getString(cursor.getColumnIndex(USER_SCREEN_NAME));
tweet.userId = cursor.getString(cursor.getColumnIndex(USER_ID));
tweet.text = cursor.getString(cursor.getColumnIndex(TEXT));
tweet.source = cursor.getString(cursor.getColumnIndex(SOURCE));
tweet.profileImageUrl = cursor.getString(cursor.getColumnIndex(PROFILE_IMAGE_URL));
tweet.inReplyToScreenName = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_SCREEN_NAME));
tweet.inReplyToStatusId = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_STATUS_ID));
tweet.inReplyToUserId = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_USER_ID));
tweet.truncated = cursor.getString(cursor.getColumnIndex(TRUNCATED));
tweet.thumbnail_pic = cursor.getString(cursor.getColumnIndex(PIC_THUMB));
tweet.bmiddle_pic = cursor.getString(cursor.getColumnIndex(PIC_MID));
tweet.original_pic = cursor.getString(cursor.getColumnIndex(PIC_ORIG));
tweet.setStatusType(cursor.getInt(cursor.getColumnIndex(STATUS_TYPE)) );
return tweet;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db/StatusTable.java | Java | asf20 | 6,715 |
package com.ch_linghu.fanfoudroid.db;
/**
* All information of status table
*
*/
public final class StatusTablesInfo {
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db/StatusTablesInfo.java | Java | asf20 | 136 |
package com.ch_linghu.fanfoudroid.db;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.dao.StatusDAO;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* A Database which contains all statuses and direct-messages, use
* getInstane(Context) to get a new instance
*
*/
public class TwitterDatabase {
private static final String TAG = "TwitterDatabase";
private static final String DATABASE_NAME = "status_db";
private static final int DATABASE_VERSION = 1;
private static TwitterDatabase instance = null;
private static DatabaseHelper mOpenHelper = null;
private Context mContext = null;
/**
* SQLiteOpenHelper
*
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
public DatabaseHelper(Context context, String name) {
this(context, name, DATABASE_VERSION);
}
public DatabaseHelper(Context context) {
this(context, DATABASE_NAME, DATABASE_VERSION);
}
public DatabaseHelper(Context context, int version) {
this(context, DATABASE_NAME, null, version);
}
public DatabaseHelper(Context context, String name, int version) {
this(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// Log.d(TAG, StatusTable.STATUS_TABLE_CREATE);
db.execSQL(StatusTable.CREATE_TABLE);
db.execSQL(MessageTable.CREATE_TABLE);
db.execSQL(FollowTable.CREATE_TABLE);
//2011.03.01 add beta
db.execSQL(UserInfoTable.CREATE_TABLE);
}
@Override
public synchronized void close() {
Log.d(TAG, "Close Database.");
super.close();
}
@Override
public void onOpen(SQLiteDatabase db) {
Log.d(TAG, "Open Database.");
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
dropAllTables(db);
}
private void dropAllTables(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + StatusTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + MessageTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME);
//2011.03.01 add
db.execSQL("DROP TABLE IF EXISTS "+UserInfoTable.TABLE_NAME);
}
}
private TwitterDatabase(Context context) {
mContext = context;
mOpenHelper = new DatabaseHelper(context);
}
public static synchronized TwitterDatabase getInstance(Context context) {
if (null == instance) {
return new TwitterDatabase(context);
}
return instance;
}
// 测试用
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
public static SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
public void close() {
if (null != instance) {
mOpenHelper.close();
instance = null;
}
}
/**
* 清空所有表中数据, 谨慎使用
*
*/
public void clearData() {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.execSQL("DELETE FROM " + StatusTable.TABLE_NAME);
db.execSQL("DELETE FROM " + MessageTable.TABLE_NAME);
db.execSQL("DELETE FROM " + FollowTable.TABLE_NAME);
//2011.03.01 add
db.execSQL("DELETE FROM "+UserInfoTable.TABLE_NAME);
}
/**
* 直接删除数据库文件, 调试用
*
* @return true if this file was deleted, false otherwise.
* @deprecated
*/
private boolean deleteDatabase() {
File dbFile = mContext.getDatabasePath(DATABASE_NAME);
return dbFile.delete();
}
/**
* 取出某类型的一条消息
*
* @param tweetId
* @param type of status
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
* @return 将Cursor转换过的Tweet对象
* @deprecated use StatusDAO#findStatus()
*/
public Tweet queryTweet(String tweetId, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
String selection = StatusTable._ID + "=? ";
if (-1 != type) {
selection += " AND " + StatusTable.STATUS_TYPE + "=" + type;
}
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
StatusTable.TABLE_COLUMNS, selection, new String[] { tweetId },
null, null, null);
Tweet tweet = null;
if (cursor != null) {
cursor.moveToFirst();
if (cursor.getCount() > 0) {
tweet = StatusTable.parseCursor(cursor);
}
}
cursor.close();
return tweet;
}
/**
* 快速检查某条消息是否存在(指定类型)
*
* @param tweetId
* @param type
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* @return is exists
* @deprecated use StatusDAO#isExists()
*/
public boolean isExists(String tweetId, String owner, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
boolean result = false;
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
new String[] { StatusTable._ID }, StatusTable._ID + " =? AND "
+ StatusTable.OWNER_ID + "=? AND "
+ StatusTable.STATUS_TYPE + " = " + type,
new String[] { tweetId, owner }, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 删除一条消息
*
* @param tweetId
* @param type -1 means all types
* @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.
* @deprecated use {@link StatusDAO#deleteStatus(String, String, int)}
*/
public int deleteTweet(String tweetId, String owner, int type) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String where = StatusTable._ID + " =? ";
if (!TextUtils.isEmpty(owner)){
where += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (-1 != type) {
where += " AND " + StatusTable.STATUS_TYPE + " = " + type;
}
return db.delete(StatusTable.TABLE_NAME, where, new String[] { tweetId });
}
/**
* 删除超过MAX_ROW_NUM垃圾数据
*
* @param type
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
*/
public void gc(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
String sql = "DELETE FROM " + StatusTable.TABLE_NAME
+ " WHERE " + StatusTable._ID + " NOT IN "
+ " (SELECT " + StatusTable._ID // 子句
+ " FROM " + StatusTable.TABLE_NAME;
boolean first = true;
if (!TextUtils.isEmpty(owner)){
sql += " WHERE " + StatusTable.OWNER_ID + " = '" + owner + "' ";
first = false;
}
if (type != -1){
if (first){
sql += " WHERE ";
}else{
sql += " AND ";
}
sql += StatusTable.STATUS_TYPE + " = " + type + " ";
}
sql += " ORDER BY " + StatusTable.CREATED_AT + " DESC LIMIT "
+ StatusTable.MAX_ROW_NUM + ")";
if (!TextUtils.isEmpty(owner)){
sql += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (type != -1) {
sql += " AND " + StatusTable.STATUS_TYPE + " = " + type + " ";
}
Log.v(TAG, sql);
mDb.execSQL(sql);
}
public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
private static final int CONFLICT_REPLACE = 0x00000005;
/**
* 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets()
*
* @param tweet
* 需要写入的单条消息
* @return the row ID of the newly inserted row, or -1 if an error occurred
* @deprecated use {@link StatusDAO#insertStatus(Status, boolean)}
*/
public long insertTweet(Tweet tweet, String owner, int type, boolean isUnread) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
if (isExists(tweet.id, owner, type)) {
Log.w(TAG, tweet.id + "is exists.");
return -1;
}
ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread);
long id = Db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
//Log.v(TAG, "Insert a status into database : " + tweet.toString());
}
return id;
}
/**
* 更新一条消息
*
* @param tweetId
* @param values
* ContentValues 需要更新字段的键值对
* @return the number of rows affected
* @deprecated use {@link StatusDAO#updateStatus(String, ContentValues)}
*/
public int updateTweet(String tweetId, ContentValues values) {
Log.v(TAG, "Update Tweet : " + tweetId + " " + values.toString());
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
return Db.update(StatusTable.TABLE_NAME, values,
StatusTable._ID + "=?", new String[] { tweetId });
}
/** @deprecated */
private ContentValues makeTweetValues(Tweet tweet, String owner, int type, boolean isUnread) {
// 插入一条新消息
ContentValues initialValues = new ContentValues();
initialValues.put(StatusTable.OWNER_ID, owner);
initialValues.put(StatusTable.STATUS_TYPE, type);
initialValues.put(StatusTable._ID, tweet.id);
initialValues.put(StatusTable.TEXT, tweet.text);
initialValues.put(StatusTable.USER_ID, tweet.userId);
initialValues.put(StatusTable.USER_SCREEN_NAME, tweet.screenName);
initialValues.put(StatusTable.PROFILE_IMAGE_URL,
tweet.profileImageUrl);
initialValues.put(StatusTable.PIC_THUMB, tweet.thumbnail_pic);
initialValues.put(StatusTable.PIC_MID, tweet.bmiddle_pic);
initialValues.put(StatusTable.PIC_ORIG, tweet.original_pic);
initialValues.put(StatusTable.FAVORITED, tweet.favorited);
initialValues.put(StatusTable.IN_REPLY_TO_STATUS_ID,
tweet.inReplyToStatusId);
initialValues.put(StatusTable.IN_REPLY_TO_USER_ID,
tweet.inReplyToUserId);
initialValues.put(StatusTable.IN_REPLY_TO_SCREEN_NAME,
tweet.inReplyToScreenName);
// initialValues.put(FIELD_IS_REPLY, tweet.isReply());
initialValues.put(StatusTable.CREATED_AT,
DB_DATE_FORMATTER.format(tweet.createdAt));
initialValues.put(StatusTable.SOURCE, tweet.source);
initialValues.put(StatusTable.IS_UNREAD, isUnread);
initialValues.put(StatusTable.TRUNCATED, tweet.truncated);
// TODO: truncated
return initialValues;
}
/**
* 写入N条消息
*
* @param tweets
* 需要写入的消息List
* @return
* 写入的记录条数
*/
public int putTweets(List<Tweet> tweets, String owner, int type, boolean isUnread) {
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("Status DB");
}
if (null == tweets || 0 == tweets.size())
{
return 0;
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int result = 0;
try {
db.beginTransaction();
for (int i = tweets.size() - 1; i >= 0; i--) {
Tweet tweet = tweets.get(i);
ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread);
long id = db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
++result;
//Log.v(TAG, String.format("Insert a status into database[%s] : %s", owner, tweet.toString()));
Log.v("TAG", "Insert Status");
}
}
// gc(type); // 保持总量
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("Status DB");
}
return result;
}
/**
* 取出指定用户的某一类型的所有消息
*
* @param userId
* @param tableName
* @return a cursor
* @deprecated use {@link StatusDAO#findStatuses(String, int)}
*/
public Cursor fetchAllTweets(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS,
StatusTable.OWNER_ID + " = ? AND " + StatusTable.STATUS_TYPE + " = " + type,
new String[]{owner}, null, null,
StatusTable.CREATED_AT + " DESC ");
//LIMIT " + StatusTable.MAX_ROW_NUM);
}
/**
* 取出自己的某一类型的所有消息
*
* @param tableName
* @return a cursor
*/
public Cursor fetchAllTweets(int type) {
// 获取登录用户id
SharedPreferences preferences = TwitterApplication.mPref;
String myself = preferences.getString(Preferences.CURRENT_USER_ID,
TwitterApplication.mApi.getUserId());
return fetchAllTweets(myself, type);
}
/**
* 清空某类型的所有信息
*
* @param tableName
* @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 dropAllTweets(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.delete(StatusTable.TABLE_NAME, StatusTable.STATUS_TYPE
+ " = " + type, null);
}
/**
* 取出本地某类型最新消息ID
*
* @param type
* @return The newest Status Id
*/
public String fetchMaxTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, true);
}
/**
* 取出本地某类型最旧消息ID
*
* @param tableName
* @return The oldest Status Id
*/
public String fetchMinTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, false);
}
private String fetchMaxOrMinTweetId(String owner, int type, boolean isMax) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String sql = "SELECT " + StatusTable._ID + " FROM "
+ StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' "
+ " ORDER BY "
+ StatusTable.CREATED_AT;
if (isMax)
sql += " DESC ";
Cursor mCursor = mDb.rawQuery(sql + " LIMIT 1", null);
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
/**
* Count unread tweet
*
* @param tableName
* @return
*/
public int fetchUnreadCount(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + StatusTable._ID + ")"
+ " FROM " + StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' AND "
+ StatusTable.IS_UNREAD + " = 1 ",
// "LIMIT " + StatusTable.MAX_ROW_NUM,
null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public int addNewTweetsAndCountUnread(List<Tweet> tweets, String owner, int type) {
putTweets(tweets, owner, type, true);
return fetchUnreadCount(owner, type);
}
/**
* Set isFavorited
*
* @param tweetId
* @param isFavorited
* @return Is Succeed
* @deprecated use {@link Status#setFavorited(boolean)} and
* {@link StatusDAO#updateStatus(Status)}
*/
public boolean setFavorited(String tweetId, String isFavorited) {
ContentValues values = new ContentValues();
values.put(StatusTable.FAVORITED, isFavorited);
int i = updateTweet(tweetId, values);
return (i > 0) ? true : false;
}
// DM & Follower
/**
* 写入一条私信
*
* @param dm
* @param isUnread
* @return the row ID of the newly inserted row, or -1 if an error occurred,
* 因为主键的原因,此处返回的不是 _ID 的值, 而是一个自增长的 row_id
*/
public long createDm(Dm dm, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(MessageTable._ID, dm.id);
initialValues.put(MessageTable.FIELD_USER_SCREEN_NAME, dm.screenName);
initialValues.put(MessageTable.FIELD_TEXT, dm.text);
initialValues.put(MessageTable.FIELD_PROFILE_IMAGE_URL,
dm.profileImageUrl);
initialValues.put(MessageTable.FIELD_IS_UNREAD, isUnread);
initialValues.put(MessageTable.FIELD_IS_SENT, dm.isSent);
initialValues.put(MessageTable.FIELD_CREATED_AT,
DB_DATE_FORMATTER.format(dm.createdAt));
initialValues.put(MessageTable.FIELD_USER_ID, dm.userId);
return mDb.insert(MessageTable.TABLE_NAME, null, initialValues);
}
//
/**
* Create a follower
*
* @param userId
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(FollowTable._ID, userId);
long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues);
if (-1 == rowId) {
Log.e(TAG, "Cann't create Follower : " + userId);
} else {
Log.v(TAG, "Success create follower : " + userId);
}
return rowId;
}
/**
* 清空Followers表并添加新内容
*
* @param followers
*/
public void syncFollowers(List<String> followers) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
boolean result = deleteAllFollowers();
Log.v(TAG, "Result of DeleteAllFollowers: " + result);
for (String userId : followers) {
createFollower(userId);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
/**
* @param type
* <li>MessageTable.TYPE_SENT</li>
* <li>MessageTable.TYPE_GET</li>
* <li>其他任何值都认为取出所有类型</li>
* @return
*/
public Cursor fetchAllDms(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String selection = null;
if (MessageTable.TYPE_SENT == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_SENT;
} else if (MessageTable.TYPE_GET == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_GET;
}
return mDb.query(MessageTable.TABLE_NAME, MessageTable.TABLE_COLUMNS,
selection, null, null, null, MessageTable.FIELD_CREATED_AT
+ " DESC");
}
public Cursor fetchInboxDms() {
return fetchAllDms(MessageTable.TYPE_GET);
}
public Cursor fetchSendboxDms() {
return fetchAllDms(MessageTable.TYPE_SENT);
}
public Cursor fetchAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS,
null, null, null, null, null);
}
/**
* FIXME:
* @param filter
* @return
*/
public Cursor getFollowerUsernames(String filter) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String likeFilter = '%' + filter + '%';
// FIXME: 此方法的作用应该是在于在写私信时自动完成联系人的功能,
// 改造数据库后,因为本地tweets表中的数据有限, 所以几乎使得该功能没有实际价值(因为能从数据库中读到的联系人很少)
// 在完成关注者/被关注者两个界面后, 看能不能使得本地有一份
// [互相关注] 的 id/name 缓存(即getFriendsIds和getFollowersIds的交集, 因为客户端只能给他们发私信, 如果按现在
// 只提示followers的列表则很容易造成服务器返回"只能给互相关注的人发私信"的错误信息, 这会造成用户无法理解, 因为此联系人是我们提供给他们选择的,
// 并且将目前的自动完成功能的基础上加一个[选择联系人]按钮, 用于启动一个新的联系人列表页面以显示所有可发送私信的联系人对象, 类似手机写短信时的选择联系人功能
return null;
// FIXME: clean this up. 新数据库中失效, 表名, 列名
// return mDb.rawQuery(
// "SELECT user_id AS _id, user"
// + " FROM (SELECT user_id, user FROM tweets"
// + " INNER JOIN followers on tweets.user_id = followers._id UNION"
// + " SELECT user_id, user FROM dms INNER JOIN followers"
// + " on dms.user_id = followers._id)"
// + " WHERE user LIKE ?"
// + " ORDER BY user COLLATE NOCASE",
// new String[] { likeFilter });
}
/**
* @param userId
* 该用户是否follow Me
* @deprecated 未使用
* @return
*/
public boolean isFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor cursor = mDb.query(FollowTable.TABLE_NAME,
FollowTable.TABLE_COLUMNS, FollowTable._ID + "= ?",
new String[] { userId }, null, null, null);
boolean result = false;
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
cursor.close();
return result;
}
public boolean deleteAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(FollowTable.TABLE_NAME, null, null) > 0;
}
public boolean deleteDm(String id) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME,
String.format("%s = '%s'", MessageTable._ID, id), null) > 0;
}
/**
* @param tableName
* @return the number of rows affected
*/
public int markAllTweetsRead(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(StatusTable.IS_UNREAD, 0);
return mDb.update(StatusTable.TABLE_NAME, values,
StatusTable.STATUS_TYPE + "=" + type, null);
}
public boolean deleteAllDms() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME, null, null) > 0;
}
public int markAllDmsRead() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MessageTable.FIELD_IS_UNREAD, 0);
return mDb.update(MessageTable.TABLE_NAME, values, null, null);
}
public String fetchMaxDmId(boolean isSent) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT " + MessageTable._ID + " FROM "
+ MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_SENT + " = ? " + " ORDER BY "
+ MessageTable.FIELD_CREATED_AT + " DESC LIMIT 1",
new String[] { isSent ? "1" : "0" });
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
public int addNewDmsAndCountUnread(List<Dm> dms) {
addDms(dms, true);
return fetchUnreadDmCount();
}
public int fetchDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME, null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
private int fetchUnreadDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_UNREAD + " = 1", null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public void addDms(List<Dm> dms, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (Dm dm : dms) {
createDm(dm, isUnread);
}
// limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT);
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
//2011.03.01 add
//UserInfo操作
public Cursor getAllUserInfo(){
SQLiteDatabase mDb=mOpenHelper.getReadableDatabase();
return mDb.query(UserInfoTable.TABLE_NAME,UserInfoTable.TABLE_COLUMNS, null, null, null, null, null);
}
/**
* 根据id列表获取user数据
* @param userIds
* @return
*/
public Cursor getUserInfoByIds(String[] userIds){
SQLiteDatabase mDb=mOpenHelper.getReadableDatabase();
String userIdStr="";
for(String id:userIds){
userIdStr+="'"+id+"',";
}
if(userIds.length==0){
userIdStr="'',";
}
userIdStr=userIdStr.substring(0, userIdStr.lastIndexOf(","));//删除最后的逗号
return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID+" in ("+userIdStr+")", null, null, null, null);
}
/**
* 新建用户
*
* @param user
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createUserInfo(com.ch_linghu.fanfoudroid.data.User user) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(UserInfoTable._ID, user.id);
initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name);
initialValues.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location);
initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
initialValues.put(UserInfoTable.FIELD_URL, user.url);
initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
//long rowId = mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
long rowId = insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, initialValues, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't create user : " + user.id);
} else {
Log.v(TAG, "create create user : " + user.id);
}
return rowId;
}
//SQLiteDatabase.insertWithConflict是LEVEL 8(2.2)才引入的新方法
//为了兼容旧版,这里给出一个简化的兼容实现
//要注意的是这个实现和标准的函数行为并不完全一致
private long insertWithOnConflict(SQLiteDatabase db, String tableName,
String nullColumnHack, ContentValues initialValues, int conflictReplace) {
long rowId = db.insert(tableName, nullColumnHack, initialValues);
if(-1 == rowId){
//尝试update
rowId = db.update(tableName, initialValues,
UserInfoTable._ID+"="+initialValues.getAsString(UserInfoTable._ID), null);
}
return rowId;
}
public long createWeiboUserInfo(com.ch_linghu.fanfoudroid.fanfou.User user){
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getId());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME,
user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT,
user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
//long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, args);
//省去判断existUser,如果存在数据则replace
//long rowId=mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, args, SQLiteDatabase.CONFLICT_REPLACE);
long rowId=insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, args, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't createWeiboUserInfo : " + user.getId());
} else {
Log.v(TAG, "create createWeiboUserInfo : " + user.getId());
}
return rowId;
}
/**
* 查看数据是否已保存用户数据
* @param userId
* @return
*/
public boolean existsUser(String userId) {
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
boolean result = false;
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
new String[] { UserInfoTable._ID }, UserInfoTable._ID +"='"+userId+"'",
null, null, null, null);
Log.v("testesetesteste", String.valueOf(cursor.getCount()));
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 根据userid提取信息
* @param userId
* @return
*/
public Cursor getUserInfoById(String userId){
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '" +userId+"'",
null, null, null, null);
return cursor;
}
/**
* 更新用户
* @param uid
* @param args
* @return
*/
public boolean updateUser(String uid,ContentValues args){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+uid+"'", null)>0;
}
/**
* 更新用户信息
*/
public boolean updateUser(com.ch_linghu.fanfoudroid.data.User user){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
ContentValues args=new ContentValues();
args.put(UserInfoTable._ID, user.id);
args.put(UserInfoTable.FIELD_USER_NAME, user.name);
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
args.put(UserInfoTable.FIELD_LOCALTION, user.location);
args.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
args.put(UserInfoTable.FIELD_URL, user.url);
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
args.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.id+"'", null)>0;
}
/**
* 减少转换的开销
* @param user
* @return
*/
public boolean updateWeiboUser(com.ch_linghu.fanfoudroid.fanfou.User user){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getName());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME,
user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT,
user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.getId()+"'", null)>0;
}
/**
* 同步用户,更新已存在的用户,插入未存在的用户
*/
public void syncUsers(List<com.ch_linghu.fanfoudroid.data.User> users){
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try{
mDb.beginTransaction();
for(com.ch_linghu.fanfoudroid.data.User u:users){
// if(existsUser(u.id)){
// updateUser(u);
// }else{
// createUserInfo(u);
// }
createUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
public void syncWeiboUsers(List<com.ch_linghu.fanfoudroid.fanfou.User> users) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (com.ch_linghu.fanfoudroid.fanfou.User u : users) {
// if (existsUser(u.getId())) {
// updateWeiboUser(u);
// } else {
// createWeiboUserInfo(u);
// }
createWeiboUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db/TwitterDatabase.java | Java | asf20 | 39,471 |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Dm;
/**
* Table - Direct Messages
*
*/
public final class MessageTable implements BaseColumns {
public static final String TAG = "MessageTable";
public static final int TYPE_GET = 0;
public static final int TYPE_SENT = 1;
public static final String TABLE_NAME = "message";
public static final int MAX_ROW_NUM = 20;
public static final String FIELD_USER_ID = "uid";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_TEXT = "text";
public static final String FIELD_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String FIELD_IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String FIELD_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FIELD_IS_UNREAD = "is_unread";
public static final String FIELD_IS_SENT = "is_send";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_SCREEN_NAME, FIELD_TEXT, FIELD_PROFILE_IMAGE_URL,
FIELD_IS_UNREAD, FIELD_IS_SENT, FIELD_CREATED_AT, FIELD_USER_ID };
public static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_SCREEN_NAME + " text not null, "
+ FIELD_TEXT + " text not null, "
+ FIELD_PROFILE_IMAGE_URL + " text not null, "
+ FIELD_IS_UNREAD + " boolean not null, "
+ FIELD_IS_SENT + " boolean not null, "
+ FIELD_CREATED_AT + " date not null, "
+ FIELD_USER_ID + " text)";
/**
* TODO: 将游标解析为一条私信
*
* @param cursor 该方法不会关闭游标
* @return 成功返回Dm类型的单条数据, 失败返回null
*/
public static Dm parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
Dm dm = new Dm();
dm.id = cursor.getString(cursor.getColumnIndex(MessageTable._ID));
dm.screenName = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_SCREEN_NAME));
dm.text = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_TEXT));
dm.profileImageUrl = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_PROFILE_IMAGE_URL));
dm.isSent = (0 == cursor.getInt(cursor.getColumnIndex(MessageTable.FIELD_IS_SENT))) ? false : true ;
try {
dm.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
dm.userId = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_ID));
return dm;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/db/MessageTable.java | Java | asf20 | 3,293 |
/*
* Copyright (C) 2009 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.
*/
package com.ch_linghu.fanfoudroid;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskFeedback;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//登录页面需要个性化的菜单绑定, 不直接继承 BaseActivity
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private static final String SIS_RUNNING_KEY = "running";
private String mUsername;
private String mPassword;
// Views.
private EditText mUsernameEdit;
private EditText mPasswordEdit;
private TextView mProgressText;
private Button mSigninButton;
private ProgressDialog dialog;
// Preferences.
private SharedPreferences mPreferences;
// Tasks.
private GenericTask mLoginTask;
private User user;
private TaskListener mLoginTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
onLoginBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
updateProgress((String)param);
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
onLoginSuccess();
} else {
onLoginFailure(((LoginTask)task).getMsg());
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "Login";
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
// No Title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_PROGRESS);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.login);
// TextView中嵌入HTML链接
TextView registerLink = (TextView) findViewById(R.id.register_link);
registerLink.setMovementMethod(LinkMovementMethod.getInstance());
mUsernameEdit = (EditText) findViewById(R.id.username_edit);
mPasswordEdit = (EditText) findViewById(R.id.password_edit);
// mUsernameEdit.setOnKeyListener(enterKeyHandler);
mPasswordEdit.setOnKeyListener(enterKeyHandler);
mProgressText = (TextView) findViewById(R.id.progress_text);
mProgressText.setFreezesText(true);
mSigninButton = (Button) findViewById(R.id.signin_button);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(SIS_RUNNING_KEY)) {
if (savedInstanceState.getBoolean(SIS_RUNNING_KEY)) {
Log.d(TAG, "Was previously logging in. Restart action.");
doLogin();
}
}
}
mSigninButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doLogin();
}
});
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestory");
if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) {
mLoginTask.cancel(true);
}
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).cancel();
super.onDestroy();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop");
// TODO Auto-generated method stub
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mLoginTask != null
&& mLoginTask.getStatus() == GenericTask.Status.RUNNING) {
// If the task was running, want to start it anew when the
// Activity restarts.
// This addresses the case where you user changes orientation
// in the middle of execution.
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private void enableLogin() {
mUsernameEdit.setEnabled(true);
mPasswordEdit.setEnabled(true);
mSigninButton.setEnabled(true);
}
private void disableLogin() {
mUsernameEdit.setEnabled(false);
mPasswordEdit.setEnabled(false);
mSigninButton.setEnabled(false);
}
// Login task.
private void doLogin() {
mUsername = mUsernameEdit.getText().toString();
mPassword = mPasswordEdit.getText().toString();
if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
if (!TextUtils.isEmpty(mUsername) & !TextUtils.isEmpty(mPassword) ) {
mLoginTask = new LoginTask();
mLoginTask.setListener(mLoginTaskListener);
TaskParams params = new TaskParams();
params.put("username", mUsername);
params.put("password", mPassword);
mLoginTask.execute(params);
} else {
updateProgress(getString(R.string.login_status_null_username_or_password));
}
}
}
private void onLoginBegin() {
disableLogin();
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).start(
getString(R.string.login_status_logging_in));
}
private void onLoginSuccess() {
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).success("");
updateProgress("");
mUsernameEdit.setText("");
mPasswordEdit.setText("");
Log.d(TAG, "Storing credentials.");
TwitterApplication.mApi.setCredentials(mUsername, mPassword);
Intent intent = getIntent().getParcelableExtra(Intent.EXTRA_INTENT);
String action = intent.getAction();
if (intent.getAction() == null || !Intent.ACTION_SEND.equals(action)) {
// We only want to reuse the intent if it was photo send.
// Or else default to the main activity.
intent = new Intent(this, TwitterActivity.class);
}
//发送消息给widget
Intent reflogin = new Intent(this.getBaseContext(), FanfouWidget.class);
reflogin.setAction("android.appwidget.action.APPWIDGET_UPDATE");
PendingIntent l = PendingIntent.getBroadcast(this.getBaseContext(), 0, reflogin,
PendingIntent.FLAG_UPDATE_CURRENT);
try {
l.send();
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(intent);
finish();
}
private void onLoginFailure(String reason) {
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).failed(reason);
enableLogin();
}
private class LoginTask extends GenericTask {
private String msg = getString(R.string.login_status_failure);
public String getMsg(){
return msg;
}
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
publishProgress(getString(R.string.login_status_logging_in) + "...");
try {
String username = param.getString("username");
String password = param.getString("password");
user= TwitterApplication.mApi.login(username, password);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
//TODO:确切的应该从HttpException中返回的消息中获取错误信息
//Throwable cause = e.getCause(); // Maybe null
// if (cause instanceof HttpAuthException) {
if (e instanceof HttpAuthException) {
// Invalid userName/password
msg = getString(R.string.login_status_invalid_username_or_password);
} else {
msg = getString(R.string.login_status_network_or_connection_error);
}
publishProgress(msg);
return TaskResult.FAILED;
}
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(Preferences.USERNAME_KEY, mUsername);
editor.putString(Preferences.PASSWORD_KEY,
encryptPassword(mPassword));
// add 存储当前用户的id
editor.putString(Preferences.CURRENT_USER_ID, user.getId());
editor.commit();
return TaskResult.OK;
}
}
private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doLogin();
}
return true;
}
return false;
}
};
public static String encryptPassword(String password) {
//return Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
return password;
}
public static String decryptPassword(String password) {
//return new String(Base64.decode(password, Base64.DEFAULT));
return password;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/LoginActivity.java | Java | asf20 | 11,496 |
package com.ch_linghu.fanfoudroid.task;
import java.util.Observable;
import java.util.Observer;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
public abstract class GenericTask extends
AsyncTask<TaskParams, Object, TaskResult> implements Observer {
private static final String TAG = "TaskManager";
private TaskListener mListener = null;
private Feedback mFeedback = null;
private boolean isCancelable = true;
abstract protected TaskResult _doInBackground(TaskParams... params);
public void setListener(TaskListener taskListener) {
mListener = taskListener;
}
public TaskListener getListener() {
return mListener;
}
public void doPublishProgress(Object... values) {
super.publishProgress(values);
}
@Override
protected void onCancelled() {
super.onCancelled();
if (mListener != null) {
mListener.onCancelled(this);
}
Log.d(TAG, mListener.getName() + " has been Cancelled.");
Toast.makeText(TwitterApplication.mContext, mListener.getName()
+ " has been cancelled", Toast.LENGTH_SHORT);
}
@Override
protected void onPostExecute(TaskResult result) {
super.onPostExecute(result);
if (mListener != null) {
mListener.onPostExecute(this, result);
}
if (mFeedback != null) {
mFeedback.success("");
}
/*
Toast.makeText(TwitterApplication.mContext, mListener.getName()
+ " completed", Toast.LENGTH_SHORT);
*/
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mListener != null) {
mListener.onPreExecute(this);
}
if (mFeedback != null) {
mFeedback.start("");
}
}
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
if (mListener != null) {
if (values != null && values.length > 0) {
mListener.onProgressUpdate(this, values[0]);
}
}
if (mFeedback != null) {
mFeedback.update(values[0]);
}
}
@Override
protected TaskResult doInBackground(TaskParams... params) {
TaskResult result = _doInBackground(params);
if (mFeedback != null) {
mFeedback.update(99);
}
return result;
}
public void update(Observable o, Object arg) {
if (TaskManager.CANCEL_ALL == (Integer) arg && isCancelable) {
if (getStatus() == GenericTask.Status.RUNNING) {
cancel(true);
}
}
}
public void setCancelable(boolean flag) {
isCancelable = flag;
}
public void setFeedback(Feedback feedback) {
mFeedback = feedback;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/task/GenericTask.java | Java | asf20 | 3,039 |
package com.ch_linghu.fanfoudroid.task;
import java.util.HashMap;
import org.json.JSONException;
import com.ch_linghu.fanfoudroid.http.HttpException;
/**
* 暂未使用,待观察是否今后需要此类
* @author lds
*
*/
public class TaskParams {
private HashMap<String, Object> params = null;
public TaskParams() {
params = new HashMap<String, Object>();
}
public TaskParams(String key, Object value) {
this();
put(key, value);
}
public void put(String key, Object value) {
params.put(key, value);
}
public Object get(String key) {
return params.get(key);
}
/**
* Get the boolean value associated with a key.
*
* @param key A key string.
* @return The truth.
* @throws HttpException
* if the value is not a Boolean or the String "true" or "false".
*/
public boolean getBoolean(String key) throws HttpException {
Object object = get(key);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new HttpException(key + " is not a Boolean.");
}
/**
* Get the double value associated with a key.
* @param key A key string.
* @return The numeric value.
* @throws HttpException if the key is not found or
* if the value is not a Number object and cannot be converted to a number.
*/
public double getDouble(String key) throws HttpException {
Object object = get(key);
try {
return object instanceof Number ?
((Number)object).doubleValue() :
Double.parseDouble((String)object);
} catch (Exception e) {
throw new HttpException(key + " is not a number.");
}
}
/**
* Get the int value associated with a key.
*
* @param key A key string.
* @return The integer value.
* @throws HttpException if the key is not found or if the value cannot
* be converted to an integer.
*/
public int getInt(String key) throws HttpException {
Object object = get(key);
try {
return object instanceof Number ?
((Number)object).intValue() :
Integer.parseInt((String)object);
} catch (Exception e) {
throw new HttpException(key + " is not an int.");
}
}
/**
* Get the string associated with a key.
*
* @param key A key string.
* @return A string which is the value.
* @throws JSONException if the key is not found.
*/
public String getString(String key) throws HttpException {
Object object = get(key);
return object == null ? null : object.toString();
}
/**
* Determine if the JSONObject contains a specific key.
* @param key A key string.
* @return true if the key exists in the JSONObject.
*/
public boolean has(String key) {
return this.params.containsKey(key);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/task/TaskParams.java | Java | asf20 | 3,288 |
package com.ch_linghu.fanfoudroid.task;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity;
public abstract class TaskFeedback {
private static TaskFeedback _instance = null;
public static final int DIALOG_MODE = 0x01;
public static final int REFRESH_MODE = 0x02;
public static final int PROGRESS_MODE = 0x03;
public static TaskFeedback getInstance(int type, Context context) {
switch (type) {
case DIALOG_MODE:
_instance = DialogFeedback.getInstance();
break;
case REFRESH_MODE:
_instance = RefreshAnimationFeedback.getInstance();
break;
case PROGRESS_MODE:
_instance = ProgressBarFeedback.getInstance();
}
_instance.setContext(context);
return _instance;
}
protected Context _context;
protected void setContext(Context context) {
_context = context;
}
public Context getContent() {
return _context;
}
// default do nothing
public void start(String prompt) {};
public void cancel() {};
public void success(String prompt) {};
public void success() { success(""); };
public void failed(String prompt) {};
public void showProgress(int progress) {};
}
/**
*
*/
class DialogFeedback extends TaskFeedback {
private static DialogFeedback _instance = null;
public static DialogFeedback getInstance() {
if (_instance == null) {
_instance = new DialogFeedback();
}
return _instance;
}
private ProgressDialog _dialog = null;
@Override
public void cancel() {
if (_dialog != null) {
_dialog.dismiss();
}
}
@Override
public void failed(String prompt) {
if (_dialog != null) {
_dialog.dismiss();
}
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_dialog = ProgressDialog.show(_context, "", prompt, true);
_dialog.setCancelable(true);
}
@Override
public void success(String prompt) {
if (_dialog != null) {
_dialog.dismiss();
}
}
}
/**
*
*/
class RefreshAnimationFeedback extends TaskFeedback {
private static RefreshAnimationFeedback _instance = null;
public static RefreshAnimationFeedback getInstance() {
if (_instance == null) {
_instance = new RefreshAnimationFeedback();
}
return _instance;
}
private WithHeaderActivity _activity;
@Override
protected void setContext(Context context) {
super.setContext(context);
_activity = (WithHeaderActivity) context;
}
@Override
public void cancel() {
_activity.setRefreshAnimation(false);
}
@Override
public void failed(String prompt) {
_activity.setRefreshAnimation(false);
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_activity.setRefreshAnimation(true);
}
@Override
public void success(String prompt) {
_activity.setRefreshAnimation(false);
}
}
/**
*
*/
class ProgressBarFeedback extends TaskFeedback {
private static ProgressBarFeedback _instance = null;
public static ProgressBarFeedback getInstance() {
if (_instance == null) {
_instance = new ProgressBarFeedback();
}
return _instance;
}
private WithHeaderActivity _activity;
@Override
protected void setContext(Context context) {
super.setContext(context);
_activity = (WithHeaderActivity) context;
}
@Override
public void cancel() {
_activity.setGlobalProgress(0);
}
@Override
public void failed(String prompt) {
cancel();
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_activity.setGlobalProgress(10);
}
@Override
public void success(String prompt) {
Log.d("LDS", "ON SUCCESS");
_activity.setGlobalProgress(0);
}
@Override
public void showProgress(int progress) {
_activity.setGlobalProgress(progress);
}
// mProgress.setIndeterminate(true);
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/task/TaskFeedback.java | Java | asf20 | 4,562 |
package com.ch_linghu.fanfoudroid.task;
public enum TaskResult {
OK,
FAILED,
CANCELLED,
NOT_FOLLOWED_ERROR,
IO_ERROR,
AUTH_ERROR
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/task/TaskResult.java | Java | asf20 | 141 |
package com.ch_linghu.fanfoudroid.task;
public interface TaskListener {
String getName();
void onPreExecute(GenericTask task);
void onPostExecute(GenericTask task, TaskResult result);
void onProgressUpdate(GenericTask task, Object param);
void onCancelled(GenericTask task);
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/task/TaskListener.java | Java | asf20 | 285 |
package com.ch_linghu.fanfoudroid.task;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
public class TweetCommonTask {
public static class DeleteTask extends GenericTask{
public static final String TAG="DeleteTask";
private BaseActivity activity;
public DeleteTask(BaseActivity activity){
this.activity = activity;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
com.ch_linghu.fanfoudroid.fanfou.Status status = null;
status = activity.getApi().destroyStatus(id);
// 对所有相关表的对应消息都进行删除(如果存在的话)
activity.getDb().deleteTweet(status.getId(), "", -1);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
public static class FavoriteTask extends GenericTask{
private static final String TAG = "FavoriteTask";
private BaseActivity activity;
public static final String TYPE_ADD = "add";
public static final String TYPE_DEL = "del";
private String type;
public String getType(){
return type;
}
public FavoriteTask(BaseActivity activity){
this.activity = activity;
}
@Override
protected TaskResult _doInBackground(TaskParams...params){
TaskParams param = params[0];
try {
String action = param.getString("action");
String id = param.getString("id");
com.ch_linghu.fanfoudroid.fanfou.Status status = null;
if (action.equals(TYPE_ADD)) {
status = activity.getApi().createFavorite(id);
activity.getDb().setFavorited(id, "true");
type = TYPE_ADD;
} else {
status = activity.getApi().destroyFavorite(id);
activity.getDb().setFavorited(id, "false");
type = TYPE_DEL;
}
Tweet tweet = Tweet.create(status);
// if (!Utils.isEmpty(tweet.profileImageUrl)) {
// // Fetch image to cache.
// try {
// activity.getImageManager().put(tweet.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
if(action.equals(TYPE_DEL)){
activity.getDb().deleteTweet(tweet.id, TwitterApplication.getMyselfId(), StatusTable.TYPE_FAVORITE);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// public static class UserTask extends GenericTask{
//
// @Override
// protected TaskResult _doInBackground(TaskParams... params) {
// // TODO Auto-generated method stub
// return null;
// }
//
// }
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/task/TweetCommonTask.java | Java | asf20 | 2,898 |
package com.ch_linghu.fanfoudroid.task;
public abstract class TaskAdapter implements TaskListener {
public abstract String getName();
public void onPreExecute(GenericTask task) {};
public void onPostExecute(GenericTask task, TaskResult result) {};
public void onProgressUpdate(GenericTask task, Object param) {};
public void onCancelled(GenericTask task) {};
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/task/TaskAdapter.java | Java | asf20 | 384 |
package com.ch_linghu.fanfoudroid.task;
import java.util.Observable;
import java.util.Observer;
import android.util.Log;
public class TaskManager extends Observable {
private static final String TAG = "TaskManager";
public static final Integer CANCEL_ALL = 1;
public void cancelAll() {
Log.d(TAG, "All task Cancelled.");
setChanged();
notifyObservers(CANCEL_ALL);
}
public void addTask(Observer task) {
super.addObserver(task);
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/task/TaskManager.java | Java | asf20 | 505 |
/*
* Copyright (C) 2009 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.
*/
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
public class MentionActivity extends TwitterCursorBaseActivity {
private static final String TAG = "MentionActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.REPLIES";
static final int DIALOG_WRITE_ID = 0;
public static Intent createIntent(Context context) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
public static Intent createNewTaskIntent(Context context) {
Intent intent = createIntent(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle("@提到我的");
return true;
}else{
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_mentions);
}
// for Retrievable interface
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getMentions(new Paging(maxId));
}else{
return getApi().getMentions();
}
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_MENTION, isUnread);
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getMentions(paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_MENTION;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/MentionActivity.java | Java | asf20 | 3,429 |
/*
* Copyright (C) 2009 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.
*/
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
public class TwitterActivity extends TwitterCursorBaseActivity {
private static final String TAG = "TwitterActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.TWEETS";
protected GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "DeleteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onDeleteSuccess();
} else if (result == TaskResult.IO_ERROR) {
onDeleteFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
public static Intent createIntent(Context context) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
public static Intent createNewTaskIntent(Context context) {
Intent intent = createIntent(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
mNavbar.setHeaderTitle("饭否fanfou.com");
//仅在这个页面进行schedule的处理
manageUpdateChecks();
return true;
} else {
return false;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
private int CONTEXT_DELETE_ID = getLastContextMenuId() + 1;
@Override
protected int getLastContextMenuId() {
return CONTEXT_DELETE_ID;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Tweet tweet = getContextItemTweet(info.position);
if (null != tweet) {// 当按钮为 刷新/更多的时候为空
if (tweet.userId.equals(TwitterApplication.getMyselfId())) {
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
if (item.getItemId() == CONTEXT_DELETE_ID) {
doDelete(tweet.id);
return true;
} else {
return super.onContextItemSelected(item);
}
}
@SuppressWarnings("deprecation")
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME);
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_home);
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_HOME);
}
// hasRetrieveListTask interface
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
// 获取消息的时候,将status里获取的user也存储到数据库
// ::MARK::
for (Tweet t : tweets) {
getDb().createWeiboUserInfo(t.user);
}
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_HOME,
isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_HOME);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null) {
return getApi().getFriendsTimeline(new Paging(maxId));
} else {
return getApi().getFriendsTimeline();
}
}
public void onDeleteFailure() {
Log.e(TAG, "Delete failed");
}
public void onDeleteSuccess() {
mTweetAdapter.refresh();
}
private void doDelete(String id) {
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new TweetCommonTask.DeleteTask(this);
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_HOME);
}
@Override
public List<Status> getMoreMessageFromId(String minId) throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getFriendsTimeline(paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_HOME;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/TwitterActivity.java | Java | asf20 | 7,741 |
package com.ch_linghu.fanfoudroid.data2;
import java.util.Date;
public class Status {
private Date created_at;
private String id;
private String text;
private String source;
private boolean truncated;
private String in_reply_to_status_id;
private String in_reply_to_user_id;
private boolean favorited;
private String in_reply_to_screen_name;
private Photo photo_url;
private User user;
private boolean isUnRead = false;
private int type = -1;
private String owner_id;
public Status() {}
public Date getCreatedAt() {
return created_at;
}
public void setCreatedAt(Date created_at) {
this.created_at = created_at;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public boolean isTruncated() {
return truncated;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
public String getInReplyToStatusId() {
return in_reply_to_status_id;
}
public void setInReplyToStatusId(String in_reply_to_status_id) {
this.in_reply_to_status_id = in_reply_to_status_id;
}
public String getInReplyToUserId() {
return in_reply_to_user_id;
}
public void setInReplyToUserId(String in_reply_to_user_id) {
this.in_reply_to_user_id = in_reply_to_user_id;
}
public boolean isFavorited() {
return favorited;
}
public void setFavorited(boolean favorited) {
this.favorited = favorited;
}
public String getInReplyToScreenName() {
return in_reply_to_screen_name;
}
public void setInReplyToScreenName(String in_reply_to_screen_name) {
this.in_reply_to_screen_name = in_reply_to_screen_name;
}
public Photo getPhotoUrl() {
return photo_url;
}
public void setPhotoUrl(Photo photo_url) {
this.photo_url = photo_url;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isUnRead() {
return isUnRead;
}
public void setUnRead(boolean isUnRead) {
this.isUnRead = isUnRead;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getOwnerId() {
return owner_id;
}
public void setOwnerId(String owner_id) {
this.owner_id = owner_id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (owner_id == null) {
if (other.owner_id != null)
return false;
} else if (!owner_id.equals(other.owner_id))
return false;
if (type != other.type)
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
@Override
public String toString() {
return "Status [created_at=" + created_at + ", id=" + id + ", text="
+ text + ", source=" + source + ", truncated=" + truncated
+ ", in_reply_to_status_id=" + in_reply_to_status_id
+ ", in_reply_to_user_id=" + in_reply_to_user_id
+ ", favorited=" + favorited + ", in_reply_to_screen_name="
+ in_reply_to_screen_name + ", photo_url=" + photo_url
+ ", user=" + user + "]";
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data2/Status.java | Java | asf20 | 4,203 |
package com.ch_linghu.fanfoudroid.data2;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DataUtils {
static SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
public static Date parseDate(String str, String format) throws ParseException {
if (str == null || "".equals(str)) {
return null;
}
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.parse(str);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data2/DataUtils.java | Java | asf20 | 570 |
package com.ch_linghu.fanfoudroid.data2;
import java.util.Date;
public class User {
private String id;
private String name;
private String screen_name;
private String location;
private String desription;
private String profile_image_url;
private String url;
private boolean isProtected;
private int friends_count;
private int followers_count;
private int favourites_count;
private Date created_at;
private boolean following;
private boolean notifications;
private int utc_offset;
private Status status; // null
public User() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScreenName() {
return screen_name;
}
public void setScreenName(String screen_name) {
this.screen_name = screen_name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDesription() {
return desription;
}
public void setDesription(String desription) {
this.desription = desription;
}
public String getProfileImageUrl() {
return profile_image_url;
}
public void setProfileImageUrl(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isProtected() {
return isProtected;
}
public void setProtected(boolean isProtected) {
this.isProtected = isProtected;
}
public int getFriendsCount() {
return friends_count;
}
public void setFriendsCount(int friends_count) {
this.friends_count = friends_count;
}
public int getFollowersCount() {
return followers_count;
}
public void setFollowersCount(int followers_count) {
this.followers_count = followers_count;
}
public int getFavouritesCount() {
return favourites_count;
}
public void setFavouritesCount(int favourites_count) {
this.favourites_count = favourites_count;
}
public Date getCreatedAt() {
return created_at;
}
public void setCreatedAt(Date created_at) {
this.created_at = created_at;
}
public boolean isFollowing() {
return following;
}
public void setFollowing(boolean following) {
this.following = following;
}
public boolean isNotifications() {
return notifications;
}
public void setNotifications(boolean notifications) {
this.notifications = notifications;
}
public int getUtcOffset() {
return utc_offset;
}
public void setUtcOffset(int utc_offset) {
this.utc_offset = utc_offset;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", screen_name="
+ screen_name + ", location=" + location + ", desription="
+ desription + ", profile_image_url=" + profile_image_url
+ ", url=" + url + ", isProtected=" + isProtected
+ ", friends_count=" + friends_count + ", followers_count="
+ followers_count + ", favourites_count=" + favourites_count
+ ", created_at=" + created_at + ", following=" + following
+ ", notifications=" + notifications + ", utc_offset="
+ utc_offset + ", status=" + status + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data2/User.java | Java | asf20 | 4,354 |
package com.ch_linghu.fanfoudroid.data2;
public class Photo {
private String thumburl;
private String imageurl;
private String largeurl;
public Photo() {}
public String getThumburl() {
return thumburl;
}
public void setThumburl(String thumburl) {
this.thumburl = thumburl;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getLargeurl() {
return largeurl;
}
public void setLargeurl(String largeurl) {
this.largeurl = largeurl;
}
@Override
public String toString() {
return "Photo [thumburl=" + thumburl + ", imageurl=" + imageurl
+ ", largeurl=" + largeurl + "]";
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/data2/Photo.java | Java | asf20 | 815 |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MyListView;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
public class UserTimelineActivity extends TwitterListBaseActivity implements
MyListView.OnNeedMoreListener, Refreshable {
private static final String TAG = UserTimelineActivity.class
.getSimpleName();
private Feedback mFeedback;
private static final String EXTRA_USERID = "userID";
private static final String EXTRA_NAME_SHOW = "showName";
private static final String SIS_RUNNING_KEY = "running";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.USERTIMELINE";
public static Intent createIntent(String userID, String showName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_USERID, userID);
intent.putExtra(EXTRA_NAME_SHOW, showName);
return intent;
}
// State.
private User mUser;
private String mUserID;
private String mShowName;
private ArrayList<Tweet> mTweets;
private int mNextPage = 1;
// Views.
private TextView headerView;
private TextView footerView;
private MyListView mTweetList;
// 记录服务器拒绝访问的信息
private String msg;
private static final int LOADINGFLAG = 1;
private static final int SUCCESSFLAG = 2;
private static final int NETWORKERRORFLAG = 3;
private static final int AUTHERRORFLAG = 4;
private TweetArrayAdapter mAdapter;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mLoadMoreTask;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录失败, 请重新登录.");
updateHeader(AUTHERRORFLAG);
return;
} else if (result == TaskResult.OK) {
updateHeader(SUCCESSFLAG);
updateFooter(SUCCESSFLAG);
draw();
goTop();
} else if (result == TaskResult.IO_ERROR) {
mFeedback.failed("更新失败.");
updateHeader(NETWORKERRORFLAG);
}
mFeedback.success("");
}
@Override
public String getName() {
return "UserTimelineRetrieve";
}
};
private TaskListener mLoadMoreTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onLoadMoreBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mFeedback.success("");
updateFooter(SUCCESSFLAG);
draw();
}
}
@Override
public String getName() {
return "UserTimelineLoadMoreTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "_onCreate()...");
if (super._onCreate(savedInstanceState)) {
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
Intent intent = getIntent();
// get user id
mUserID = intent.getStringExtra(EXTRA_USERID);
// show username in title
mShowName = intent.getStringExtra(EXTRA_NAME_SHOW);
// Set header title
mNavbar.setHeaderTitle("@" + mShowName);
boolean wasRunning = isTrue(savedInstanceState, SIS_RUNNING_KEY);
// 此处要求mTweets不为空,最好确保profile页面消息为0时不能进入这个页面
if (!mTweets.isEmpty() && !wasRunning) {
updateHeader(SUCCESSFLAG);
draw();
} else {
doRetrieve();
}
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
mLoadMoreTask.cancel(true);
}
super.onDestroy();
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new UserTimelineRetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
private void doLoadMore() {
Log.d(TAG, "Attempting load more.");
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mLoadMoreTask = new UserTimelineLoadMoreTask();
mLoadMoreTask.setListener(mLoadMoreTaskListener);
mLoadMoreTask.execute();
}
}
private void onRetrieveBegin() {
mFeedback.start("");
// 更新查询状态显示
updateHeader(LOADINGFLAG);
updateFooter(LOADINGFLAG);
}
private void onLoadMoreBegin() {
mFeedback.start("");
}
private class UserTimelineRetrieveTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
mUser = getApi().showUser(mUserID);
mFeedback.update(60);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
mFeedback.update(100 - (int)Math.floor(statusList.size()*2)); // 60~100
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
private class UserTimelineLoadMoreTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
@Override
public void needMore() {
if (!isLastPage()) {
doLoadMore();
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
// do more时没有更多时
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return "@" + mShowName;
}
@Override
protected Tweet getContextItemTweet(int position) {
if (position >= 1 && position <= mAdapter.getCount()) {
return (Tweet) mAdapter.getItem(position - 1);
} else {
return null;
}
}
@Override
protected int getLayoutId() {
return R.layout.user_timeline;
}
@Override
protected com.ch_linghu.fanfoudroid.ui.module.TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mAdapter = new TweetArrayAdapter(this);
mTweetList = (MyListView) findViewById(R.id.tweet_list);
// Add Header to ListView
headerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_header, null);
mTweetList.addHeaderView(headerView);
// Add Footer to ListView
footerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_footer, null);
mTweetList.addFooterView(footerView);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnNeedMoreListener(this);
}
@Override
protected void updateTweet(Tweet tweet) {
// 该方法作用?
}
@Override
protected boolean useBasicMenu() {
return true;
}
private void updateHeader(int flag) {
if (flag == LOADINGFLAG) {
// 重新刷新页面时从第一页开始获取数据 --- phoenix
mNextPage = 1;
mTweets.clear();
mAdapter.refresh(mTweets);
headerView.setText(getResources()
.getString(R.string.search_loading));
}
if (flag == SUCCESSFLAG) {
headerView.setText(getResources().getString(
R.string.user_query_status_success));
}
if (flag == NETWORKERRORFLAG) {
headerView.setText(getResources().getString(
R.string.login_status_network_or_connection_error));
}
if (flag == AUTHERRORFLAG) {
headerView.setText(msg);
}
}
private void updateFooter(int flag) {
if (flag == LOADINGFLAG) {
footerView.setText("该用户总共?条消息");
}
if (flag == SUCCESSFLAG) {
footerView.setText("该用户总共" + mUser.getStatusesCount() + "条消息,当前显示"
+ mTweets.size() + "条。");
}
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/UserTimelineActivity.java | Java | asf20 | 14,047 |
/*
* Copyright (C) 2009 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.
*/
package com.ch_linghu.fanfoudroid;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
//FIXME: 将WriteDmActivity和WriteActivity进行整合。
/**
* 撰写私信界面
* @author lds
*
*/
public class WriteDmActivity extends BaseActivity {
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String EXTRA_TEXT = "text";
public static final String REPLY_ID = "reply_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private Button mSendButton;
//private AutoCompleteTextView mToEdit;
private TextView mToEdit;
private NavBar mNavbar;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
disableEntry();
updateProgress(getString(R.string.page_status_updating));
}
@Override
public void onPostExecute(GenericTask task,
TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mToEdit.setText("");
mTweetEdit.setText("");
updateProgress("");
enableEntry();
// 发送成功就直接关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(), 0);
} else if (result == TaskResult.NOT_FOLLOWED_ERROR) {
updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you));
enableEntry();
} else if (result == TaskResult.IO_ERROR) {
// TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
}
@Override
public String getName() {
return "DMSend";
}
};
private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient
// autocomplete.
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW";
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
// sub menu
// protected void createInsertPhotoDialog() {
//
// final CharSequence[] items = {
// getString(R.string.write_label_take_a_picture),
// getString(R.string.write_label_choose_a_picture) };
//
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle(getString(R.string.write_label_insert_picture));
// builder.setItems(items, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int item) {
// // Toast.makeText(getApplicationContext(), items[item],
// // Toast.LENGTH_SHORT).show();
// switch (item) {
// case 0:
// openImageCaptureMenu();
// break;
// case 1:
// openPhotoLibraryMenu();
// }
// }
// });
// AlertDialog alert = builder.create();
// alert.show();
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)){
// init View
setContentView(R.layout.write_dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
Bundle extras = intent.getExtras();
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
TwitterDatabase db = getDb();
//FIXME: 暂时取消收件人自动完成功能
//FIXME: 可根据目前以后内容重新完成自动完成功能
//mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit);
//Cursor cursor = db.getFollowerUsernames("");
//// startManagingCursor(cursor);
//mFriendsAdapter = new FriendsAdapter(this, cursor);
//mToEdit.setAdapter(mFriendsAdapter);
mToEdit = (TextView) findViewById(R.id.to_edit);
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
mTweetEdit.setOnKeyListener(editEnterHandler);
mTweetEdit
.addTextChangedListener(new MyTextWatcher(WriteDmActivity.this));
// With extras
if (extras != null) {
String to = extras.getString(EXTRA_USER);
if (!TextUtils.isEmpty(to)) {
mToEdit.setText(to);
mTweetEdit.requestFocus();
}
}
View.OnClickListener sendListenner = new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
};
mSendButton = (Button) findViewById(R.id.send_button);
mSendButton.setOnClickListener(sendListenner);
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(sendListenner);
return true;
}else{
return false;
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
mTweetEdit.updateCharsRemain();
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(EXTRA_TEXT, text);
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteDmActivity _activity;
public MyTextWatcher(WriteDmActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (s.length() == 0) {
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private void doSend() {
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String to = mToEdit.getText().toString();
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(to)) {
mSendTask = new DmSendTask();
mSendTask.setListener(mSendTaskListener);
mSendTask.execute();
} else if (TextUtils.isEmpty(status)) {
updateProgress(getString(R.string.direct_meesage_status_texting_is_null));
} else if (TextUtils.isEmpty(to)) {
updateProgress(getString(R.string.direct_meesage_status_user_is_null));
}
}
}
private class DmSendTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String user = mToEdit.getText().toString();
String text = mTweetEdit.getText().toString();
DirectMessage directMessage = getApi().sendDirectMessage(user,
text);
Dm dm = Dm.create(directMessage, true);
// if (!Utils.isEmpty(dm.profileImageUrl)) {
// // Fetch image to cache.
// try {
// getImageManager().put(dm.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
getDb().createDm(dm, false);
} catch (HttpException e) {
Log.d(TAG, e.getMessage());
// TODO: check is this is actually the case.
return TaskResult.NOT_FOLLOWED_ERROR;
}
return TaskResult.OK;
}
}
private static class FriendsAdapter extends CursorAdapter {
public FriendsAdapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater
.inflate(R.layout.dropdown_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view.findViewById(android.R.id.text1);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.userText.setText(cursor.getString(mUserTextColumn));
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String filter = constraint == null ? "" : constraint.toString();
return TwitterApplication.mDb.getFollowerUsernames(filter);
}
@Override
public String convertToString(Cursor cursor) {
return cursor.getString(mUserTextColumn);
}
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mSendButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mSendButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private View.OnKeyListener editEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doSend();
}
return true;
}
return false;
}
};
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/WriteDmActivity.java | Java | asf20 | 12,540 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing search API response
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class QueryResult extends WeiboResponse {
private long sinceId;
private long maxId;
private String refreshUrl;
private int resultsPerPage;
private int total = -1;
private String warning;
private double completedIn;
private int page;
private String query;
private List<Status> tweets;
private static final long serialVersionUID = -9059136565234613286L;
/*package*/ QueryResult(Response res, WeiboSupport weiboSupport) throws HttpException {
super(res);
// 饭否search API直接返回 "[{JSONObejet},{JSONObejet},{JSONObejet}]"的JSONArray
//System.out.println("TAG " + res.asString());
JSONArray array = res.asJSONArray();
try {
tweets = new ArrayList<Status>(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject tweet = array.getJSONObject(i);
tweets.add(new Status(tweet));
}
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + array.toString(), jsone);
}
}
/*package*/ QueryResult(Query query) throws HttpException {
super();
sinceId = query.getSinceId();
resultsPerPage = query.getRpp();
page = query.getPage();
tweets = new ArrayList<Status>(0);
}
public long getSinceId() {
return sinceId;
}
public long getMaxId() {
return maxId;
}
public String getRefreshUrl() {
return refreshUrl;
}
public int getResultsPerPage() {
return resultsPerPage;
}
/**
* returns the number of hits
* @return number of hits
* @deprecated The Weibo API doesn't return total anymore
* @see <a href="http://yusuke.homeip.net/jira/browse/TFJ-108">TRJ-108 deprecate QueryResult#getTotal()</a>
*/
@Deprecated
public int getTotal() {
return total;
}
public String getWarning() {
return warning;
}
public double getCompletedIn() {
return completedIn;
}
public int getPage() {
return page;
}
public String getQuery() {
return query;
}
public List<Status> getStatus() {
return tweets;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
QueryResult that = (QueryResult) o;
if (Double.compare(that.completedIn, completedIn) != 0) return false;
if (maxId != that.maxId) return false;
if (page != that.page) return false;
if (resultsPerPage != that.resultsPerPage) return false;
if (sinceId != that.sinceId) return false;
if (total != that.total) return false;
if (!query.equals(that.query)) return false;
if (refreshUrl != null ? !refreshUrl.equals(that.refreshUrl) : that.refreshUrl != null)
return false;
if (tweets != null ? !tweets.equals(that.tweets) : that.tweets != null)
return false;
if (warning != null ? !warning.equals(that.warning) : that.warning != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (int) (maxId ^ (maxId >>> 32));
result = 31 * result + (refreshUrl != null ? refreshUrl.hashCode() : 0);
result = 31 * result + resultsPerPage;
result = 31 * result + total;
result = 31 * result + (warning != null ? warning.hashCode() : 0);
temp = completedIn != +0.0d ? Double.doubleToLongBits(completedIn) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + page;
result = 31 * result + query.hashCode();
result = 31 * result + (tweets != null ? tweets.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "QueryResult{" +
"sinceId=" + sinceId +
", maxId=" + maxId +
", refreshUrl='" + refreshUrl + '\'' +
", resultsPerPage=" + resultsPerPage +
", total=" + total +
", warning='" + warning + '\'' +
", completedIn=" + completedIn +
", page=" + page +
", query='" + query + '\'' +
", tweets=" + tweets +
'}';
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/QueryResult.java | Java | asf20 | 6,405 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.AccessControlException;
import java.util.Properties;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Configuration {
private static Properties defaultProperty;
static {
init();
}
/*package*/ static void init() {
defaultProperty = new Properties();
//defaultProperty.setProperty("fanfoudroid.debug", "false");
defaultProperty.setProperty("fanfoudroid.debug", "true");
defaultProperty.setProperty("fanfoudroid.source", "fanfoudroid");
//defaultProperty.setProperty("fanfoudroid.clientVersion","");
defaultProperty.setProperty("fanfoudroid.clientURL", "http://sandin.tk/fanfoudroid.xml");
defaultProperty.setProperty("fanfoudroid.http.userAgent", "fanfoudroid 1.0");
//defaultProperty.setProperty("fanfoudroid.user","");
//defaultProperty.setProperty("fanfoudroid.password","");
defaultProperty.setProperty("fanfoudroid.http.useSSL", "false");
//defaultProperty.setProperty("fanfoudroid.http.proxyHost","");
defaultProperty.setProperty("fanfoudroid.http.proxyHost.fallback", "http.proxyHost");
//defaultProperty.setProperty("fanfoudroid.http.proxyUser","");
//defaultProperty.setProperty("fanfoudroid.http.proxyPassword","");
//defaultProperty.setProperty("fanfoudroid.http.proxyPort","");
defaultProperty.setProperty("fanfoudroid.http.proxyPort.fallback", "http.proxyPort");
defaultProperty.setProperty("fanfoudroid.http.connectionTimeout", "20000");
defaultProperty.setProperty("fanfoudroid.http.readTimeout", "120000");
defaultProperty.setProperty("fanfoudroid.http.retryCount", "3");
defaultProperty.setProperty("fanfoudroid.http.retryIntervalSecs", "10");
//defaultProperty.setProperty("fanfoudroid.oauth.consumerKey","");
//defaultProperty.setProperty("fanfoudroid.oauth.consumerSecret","");
defaultProperty.setProperty("fanfoudroid.async.numThreads", "1");
defaultProperty.setProperty("fanfoudroid.clientVersion", "1.0");
try {
// Android platform should have dalvik.system.VMRuntime in the classpath.
// @see http://developer.android.com/reference/dalvik/system/VMRuntime.html
Class.forName("dalvik.system.VMRuntime");
defaultProperty.setProperty("fanfoudroid.dalvik", "true");
} catch (ClassNotFoundException cnfe) {
defaultProperty.setProperty("fanfoudroid.dalvik", "false");
}
DALVIK = getBoolean("fanfoudroid.dalvik");
String t4jProps = "fanfoudroid.properties";
boolean loaded = loadProperties(defaultProperty, "." + File.separatorChar + t4jProps) ||
loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/WEB-INF/" + t4jProps)) ||
loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/" + t4jProps));
}
private static boolean loadProperties(Properties props, String path) {
try {
File file = new File(path);
if(file.exists() && file.isFile()){
props.load(new FileInputStream(file));
return true;
}
} catch (Exception ignore) {
}
return false;
}
private static boolean loadProperties(Properties props, InputStream is) {
try {
props.load(is);
return true;
} catch (Exception ignore) {
}
return false;
}
private static boolean DALVIK;
public static boolean isDalvik() {
return DALVIK;
}
public static boolean useSSL() {
return getBoolean("fanfoudroid.http.useSSL");
}
public static String getScheme(){
return useSSL() ? "https://" : "http://";
}
public static String getCilentVersion() {
return getProperty("fanfoudroid.clientVersion");
}
public static String getCilentVersion(String clientVersion) {
return getProperty("fanfoudroid.clientVersion", clientVersion);
}
public static String getSource() {
return getProperty("fanfoudroid.source");
}
public static String getSource(String source) {
return getProperty("fanfoudroid.source", source);
}
public static String getProxyHost() {
return getProperty("fanfoudroid.http.proxyHost");
}
public static String getProxyHost(String proxyHost) {
return getProperty("fanfoudroid.http.proxyHost", proxyHost);
}
public static String getProxyUser() {
return getProperty("fanfoudroid.http.proxyUser");
}
public static String getProxyUser(String user) {
return getProperty("fanfoudroid.http.proxyUser", user);
}
public static String getClientURL() {
return getProperty("fanfoudroid.clientURL");
}
public static String getClientURL(String clientURL) {
return getProperty("fanfoudroid.clientURL", clientURL);
}
public static String getProxyPassword() {
return getProperty("fanfoudroid.http.proxyPassword");
}
public static String getProxyPassword(String password) {
return getProperty("fanfoudroid.http.proxyPassword", password);
}
public static int getProxyPort() {
return getIntProperty("fanfoudroid.http.proxyPort");
}
public static int getProxyPort(int port) {
return getIntProperty("fanfoudroid.http.proxyPort", port);
}
public static int getConnectionTimeout() {
return getIntProperty("fanfoudroid.http.connectionTimeout");
}
public static int getConnectionTimeout(int connectionTimeout) {
return getIntProperty("fanfoudroid.http.connectionTimeout", connectionTimeout);
}
public static int getReadTimeout() {
return getIntProperty("fanfoudroid.http.readTimeout");
}
public static int getReadTimeout(int readTimeout) {
return getIntProperty("fanfoudroid.http.readTimeout", readTimeout);
}
public static int getRetryCount() {
return getIntProperty("fanfoudroid.http.retryCount");
}
public static int getRetryCount(int retryCount) {
return getIntProperty("fanfoudroid.http.retryCount", retryCount);
}
public static int getRetryIntervalSecs() {
return getIntProperty("fanfoudroid.http.retryIntervalSecs");
}
public static int getRetryIntervalSecs(int retryIntervalSecs) {
return getIntProperty("fanfoudroid.http.retryIntervalSecs", retryIntervalSecs);
}
public static String getUser() {
return getProperty("fanfoudroid.user");
}
public static String getUser(String userId) {
return getProperty("fanfoudroid.user", userId);
}
public static String getPassword() {
return getProperty("fanfoudroid.password");
}
public static String getPassword(String password) {
return getProperty("fanfoudroid.password", password);
}
public static String getUserAgent() {
return getProperty("fanfoudroid.http.userAgent");
}
public static String getUserAgent(String userAgent) {
return getProperty("fanfoudroid.http.userAgent", userAgent);
}
public static String getOAuthConsumerKey() {
return getProperty("fanfoudroid.oauth.consumerKey");
}
public static String getOAuthConsumerKey(String consumerKey) {
return getProperty("fanfoudroid.oauth.consumerKey", consumerKey);
}
public static String getOAuthConsumerSecret() {
return getProperty("fanfoudroid.oauth.consumerSecret");
}
public static String getOAuthConsumerSecret(String consumerSecret) {
return getProperty("fanfoudroid.oauth.consumerSecret", consumerSecret);
}
public static boolean getBoolean(String name) {
String value = getProperty(name);
return Boolean.valueOf(value);
}
public static int getIntProperty(String name) {
String value = getProperty(name);
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static int getIntProperty(String name, int fallbackValue) {
String value = getProperty(name, String.valueOf(fallbackValue));
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static long getLongProperty(String name) {
String value = getProperty(name);
try {
return Long.parseLong(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static String getProperty(String name) {
return getProperty(name, null);
}
public static String getProperty(String name, String fallbackValue) {
String value;
try {
value = System.getProperty(name, fallbackValue);
if (null == value) {
value = defaultProperty.getProperty(name);
}
if (null == value) {
String fallback = defaultProperty.getProperty(name + ".fallback");
if (null != fallback) {
value = System.getProperty(fallback);
}
}
} catch (AccessControlException ace) {
// Unsigned applet cannot access System properties
value = fallbackValue;
}
return replace(value);
}
private static String replace(String value) {
if (null == value) {
return value;
}
String newValue = value;
int openBrace = 0;
if (-1 != (openBrace = value.indexOf("{", openBrace))) {
int closeBrace = value.indexOf("}", openBrace);
if (closeBrace > (openBrace + 1)) {
String name = value.substring(openBrace + 1, closeBrace);
if (name.length() > 0) {
newValue = value.substring(0, openBrace) + getProperty(name)
+ value.substring(closeBrace + 1);
}
}
}
if (newValue.equals(value)) {
return value;
} else {
return replace(newValue);
}
}
public static int getNumberOfAsyncThreads() {
return getIntProperty("fanfoudroid.async.numThreads");
}
public static boolean getDebug() {
return getBoolean("fanfoudroid.debug");
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/Configuration.java | Java | asf20 | 12,102 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Treands.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.2
*/
public class Trends extends WeiboResponse implements Comparable<Trends> {
private Date asOf;
private Date trendAt;
private Trend[] trends;
private static final long serialVersionUID = -7151479143843312309L;
public int compareTo(Trends that) {
return this.trendAt.compareTo(that.trendAt);
}
/*package*/ Trends(Response res, Date asOf, Date trendAt, Trend[] trends)
throws HttpException {
super(res);
this.asOf = asOf;
this.trendAt = trendAt;
this.trends = trends;
}
/*package*/
static List<Trends> constructTrendsList(Response res) throws
HttpException {
JSONObject json = res.asJSONObject();
List<Trends> trends;
try {
Date asOf = parseDate(json.getString("as_of"));
JSONObject trendsJson = json.getJSONObject("trends");
trends = new ArrayList<Trends>(trendsJson.length());
Iterator ite = trendsJson.keys();
while (ite.hasNext()) {
String key = (String) ite.next();
JSONArray array = trendsJson.getJSONArray(key);
Trend[] trendsArray = jsonArrayToTrendArray(array);
if (key.length() == 19) {
// current trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd HH:mm:ss"), trendsArray));
} else if (key.length() == 16) {
// daily trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd HH:mm"), trendsArray));
} else if (key.length() == 10) {
// weekly trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd"), trendsArray));
}
}
Collections.sort(trends);
return trends;
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
/*package*/
static Trends constructTrends(Response res) throws HttpException {
JSONObject json = res.asJSONObject();
try {
Date asOf = parseDate(json.getString("as_of"));
JSONArray array = json.getJSONArray("trends");
Trend[] trendsArray = jsonArrayToTrendArray(array);
return new Trends(res, asOf, asOf, trendsArray);
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
private static Date parseDate(String asOfStr) throws HttpException {
Date parsed;
if (asOfStr.length() == 10) {
parsed = new Date(Long.parseLong(asOfStr) * 1000);
} else {
// parsed = WeiboResponse.parseDate(asOfStr, "EEE, d MMM yyyy HH:mm:ss z");
parsed = WeiboResponse.parseDate(asOfStr, "EEE MMM WW HH:mm:ss z yyyy");
}
return parsed;
}
private static Trend[] jsonArrayToTrendArray(JSONArray array) throws JSONException {
Trend[] trends = new Trend[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject trend = array.getJSONObject(i);
trends[i] = new Trend(trend);
}
return trends;
}
public Trend[] getTrends() {
return this.trends;
}
public Date getAsOf() {
return asOf;
}
public Date getTrendAt() {
return trendAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Trends)) return false;
Trends trends1 = (Trends) o;
if (asOf != null ? !asOf.equals(trends1.asOf) : trends1.asOf != null)
return false;
if (trendAt != null ? !trendAt.equals(trends1.trendAt) : trends1.trendAt != null)
return false;
if (!Arrays.equals(trends, trends1.trends)) return false;
return true;
}
@Override
public int hashCode() {
int result = asOf != null ? asOf.hashCode() : 0;
result = 31 * result + (trendAt != null ? trendAt.hashCode() : 0);
result = 31 * result + (trends != null ? Arrays.hashCode(trends) : 0);
return result;
}
@Override
public String toString() {
return "Trends{" +
"asOf=" + asOf +
", trendAt=" + trendAt +
", trends=" + (trends == null ? null : Arrays.asList(trends)) +
'}';
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/Trends.java | Java | asf20 | 6,595 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* 模仿JSONObject的XML实现
* @author jmx
*
*/
class XmlObject{
private String str;
public XmlObject(String s){
this.str = s;
}
//FIXME: 这里用的是一个专有的ugly实现
public String getString(String name) throws Exception {
Pattern p = Pattern.compile(String.format("<%s>(.*?)</%s>", name, name));
Matcher m = p.matcher(this.str);
if (m.find()){
return m.group(1);
}else{
throw new Exception(String.format("<%s> value not found", name));
}
}
@Override
public String toString(){
return this.str;
}
}
/**
* 服务器响应的错误信息
*/
public class RefuseError extends WeiboResponse implements java.io.Serializable {
// TODO: get error type
public static final int ERROR_A = 1;
public static final int ERROR_B = 1;
public static final int ERROR_C = 1;
private int mErrorCode = -1;
private String mRequestUrl = "";
private String mResponseError = "";
private static final long serialVersionUID = -2105422180879273058L;
public RefuseError(Response res) throws HttpException {
String error = res.asString();
try{
//先尝试作为json object进行处理
JSONObject json = new JSONObject(error);
init(json);
}catch(Exception e1){
//如果失败,则作为XML再进行处理
try{
XmlObject xml = new XmlObject(error);
init(xml);
}catch(Exception e2){
//再失败就作为普通字符串进行处理,这个处理保证不会出错
init(error);
}
}
}
public void init(JSONObject json) throws HttpException {
try {
mRequestUrl = json.getString("request");
mResponseError = json.getString("error");
parseError(mResponseError);
} catch (JSONException je) {
throw new HttpException(je.getMessage() + ":" + json.toString(), je);
}
}
public void init(XmlObject xml) throws HttpException {
try {
mRequestUrl = xml.getString("request");
mResponseError = xml.getString("error");
parseError(mResponseError);
} catch (Exception e) {
throw new HttpException(e.getMessage() + ":" + xml.toString(), e);
}
}
public void init(String error){
mRequestUrl = "";
mResponseError = error;
parseError(mResponseError);
}
private void parseError(String error) {
if (error.equals("")) {
mErrorCode = ERROR_A;
}
}
public int getErrorCode() {
return mErrorCode;
}
public String getRequestUrl() {
return mRequestUrl;
}
public String getMessage() {
return mResponseError;
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/RefuseError.java | Java | asf20 | 4,494 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import com.ch_linghu.fanfoudroid.http.HttpClient;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
*/
/*protected*/ class WeiboSupport {
protected HttpClient http = null;
protected String source = Configuration.getSource();
protected final boolean USE_SSL;
/*package*/ WeiboSupport(){
USE_SSL = Configuration.useSSL();
http = new HttpClient(); // In case that the user is not logged in
}
/*package*/ WeiboSupport(String userId, String password){
USE_SSL = Configuration.useSSL();
http = new HttpClient(userId, password);
}
/**
* Returns authenticating userid
*
* @return userid
*/
public String getUserId() {
return http.getUserId();
}
/**
* Returns authenticating password
*
* @return password
*/
public String getPassword() {
return http.getPassword();
}
//Low-level interface
public HttpClient getHttpClient(){
return http;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/WeiboSupport.java | Java | asf20 | 2,533 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing array of numeric IDs.
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class IDs extends WeiboResponse {
private String[] ids;
private long previousCursor;
private long nextCursor;
private static final long serialVersionUID = -6585026560164704953L;
private static String[] ROOT_NODE_NAMES = {"id_list", "ids"};
/*package*/ IDs(Response res) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
ensureRootNodeNameIs(ROOT_NODE_NAMES, elem);
NodeList idlist = elem.getElementsByTagName("id");
ids = new String[idlist.getLength()];
for (int i = 0; i < idlist.getLength(); i++) {
try {
ids[i] = idlist.item(i).getFirstChild().getNodeValue();
} catch (NumberFormatException nfe) {
throw new HttpException("Weibo API returned malformed response(Invalid Number): " + elem, nfe);
} catch (NullPointerException npe) {
throw new HttpException("Weibo API returned malformed response(NULL): " + elem, npe);
}
}
previousCursor = getChildLong("previous_cursor", elem);
nextCursor = getChildLong("next_cursor", elem);
}
/* package */IDs(Response res, Weibo w) throws HttpException {
super(res);
// TODO: 饭否返回的为 JSONArray 类型,
// 例如["ifan","fanfouapi","\u62cd\u62cd","daoru"]
// JSONObject json= res.asJSONObject();
JSONArray jsona = res.asJSONArray();
try {
int size = jsona.length();
ids = new String[size];
for (int i = 0; i < size; i++) {
ids[i] = jsona.getString(i);
}
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
public String[] getIDs() {
return ids;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean hasPrevious(){
return 0 != previousCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public long getPreviousCursor() {
return previousCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean hasNext(){
return 0 != nextCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public long getNextCursor() {
return nextCursor;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IDs)) return false;
IDs iDs = (IDs) o;
if (!Arrays.equals(ids, iDs.ids)) return false;
return true;
}
@Override
public int hashCode() {
return ids != null ? Arrays.hashCode(ids) : 0;
}
public int getCount(){
return ids.length;
}
@Override
public String toString() {
return "IDs{" +
"ids=" + ids +
", previousCursor=" + previousCursor +
", nextCursor=" + nextCursor +
'}';
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/IDs.java | Java | asf20 | 4,847 |
/*
* UserObjectWapper.java created on 2010-7-28 上午08:48:35 by bwl (Liu Daoru)
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.Serializable;
import java.util.List;
/**
* 对User对象列表进行的包装,以支持cursor相关信息传递
* @author liudaoru - daoru at sina.com.cn
*/
public class UserWapper implements Serializable {
private static final long serialVersionUID = -3119107701303920284L;
/**
* 用户对象列表
*/
private List<User> users;
/**
* 向前翻页的cursor
*/
private long previousCursor;
/**
* 向后翻页的cursor
*/
private long nextCursor;
public UserWapper(List<User> users, long previousCursor, long nextCursor) {
this.users = users;
this.previousCursor = previousCursor;
this.nextCursor = nextCursor;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public long getPreviousCursor() {
return previousCursor;
}
public void setPreviousCursor(long previousCursor) {
this.previousCursor = previousCursor;
}
public long getNextCursor() {
return nextCursor;
}
public void setNextCursor(long nextCursor) {
this.nextCursor = nextCursor;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/UserWapper.java | Java | asf20 | 1,281 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
/**
* Controlls pagination
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Paging implements java.io.Serializable {
private int page = -1;
private int count = -1;
private String sinceId = "";
private String maxId = "";
private static final long serialVersionUID = -3285857427993796670L;
public Paging() {
}
public Paging(int page) {
setPage(page);
}
public Paging(String sinceId) {
setSinceId(sinceId);
}
public Paging(int page, int count) {
this(page);
setCount(count);
}
public Paging(int page, String sinceId) {
this(page);
setSinceId(sinceId);
}
public Paging(int page, int count, String sinceId) {
this(page, count);
setSinceId(sinceId);
}
public Paging(int page, int count, String sinceId, String maxId) {
this(page, count, sinceId);
setMaxId(maxId);
}
public int getPage() {
return page;
}
public void setPage(int page) {
if (page < 1) {
throw new IllegalArgumentException("page should be positive integer. passed:" + page);
}
this.page = page;
}
public int getCount() {
return count;
}
public void setCount(int count) {
if (count < 1) {
throw new IllegalArgumentException("count should be positive integer. passed:" + count);
}
this.count = count;
}
public Paging count(int count) {
setCount(count);
return this;
}
public String getSinceId() {
return sinceId;
}
public void setSinceId(String sinceId) {
if (sinceId.length() > 0) {
this.sinceId = sinceId;
} else {
throw new IllegalArgumentException("since_id is null. passed:" + sinceId);
}
}
public Paging sinceId(String sinceId) {
setSinceId(sinceId);
return this;
}
public String getMaxId() {
return maxId;
}
public void setMaxId(String maxId) {
if (maxId.length() == 0) {
throw new IllegalArgumentException("max_id is null. passed:" + maxId);
}
this.maxId = maxId;
}
public Paging maxId(String maxId) {
setMaxId(maxId);
return this;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/Paging.java | Java | asf20 | 3,847 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
public class Weibo extends WeiboSupport implements java.io.Serializable {
public static final String TAG = "Weibo_API";
public static final String CONSUMER_KEY = Configuration.getSource();
public static final String CONSUMER_SECRET = "";
private String baseURL = Configuration.getScheme() + "api.fanfou.com/";
private String searchBaseURL = Configuration.getScheme() + "api.fanfou.com/";
private static final long serialVersionUID = -1486360080128882436L;
public Weibo() {
super(); // In case that the user is not logged in
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public Weibo(String userId, String password) {
super(userId, password);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public Weibo(String userId, String password, String baseURL) {
this(userId, password);
this.baseURL = baseURL;
}
/**
* 设置HttpClient的Auth,为请求做准备
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
http.setCredentials(username, password);
}
/**
* 仅判断是否为空
* @param username
* @param password
* @return
*/
public static boolean isValidCredentials(String username, String password) {
return !TextUtils.isEmpty(username) && !TextUtils.isEmpty(password);
}
/**
* 在服务器上验证用户名/密码是否正确,成功则返回该用户信息,失败则抛出异常。
* @param username
* @param password
* @return Verified User
* @throws HttpException 验证失败及其他非200响应均抛出异常
*/
public User login(String username, String password) throws HttpException {
Log.d(TAG, "Login attempt for " + username);
http.setCredentials(username, password);
// Verify userName and password on the server.
User user = verifyCredentials();
if (null != user && user.getId().length() > 0) {
}
return user;
}
/**
* Reset HttpClient's Credentials
*/
public void reset() {
http.reset();
}
/**
* Whether Logged-in
* @return
*/
public boolean isLoggedIn() {
// HttpClient的userName&password是由TwitterApplication#onCreate
// 从SharedPreferences中取出的,他们为空则表示尚未登录,因为他们只在验证
// 账户成功后才会被储存,且注销时被清空。
return isValidCredentials(http.getUserId(), http.getPassword());
}
/**
* Sets the base URL
*
* @param baseURL String the base URL
*/
public void setBaseURL(String baseURL) {
this.baseURL = baseURL;
}
/**
* Returns the base URL
*
* @return the base URL
*/
public String getBaseURL() {
return this.baseURL;
}
/**
* Sets the search base URL
*
* @param searchBaseURL the search base URL
* @since fanfoudroid 0.5.0
*/
public void setSearchBaseURL(String searchBaseURL) {
this.searchBaseURL = searchBaseURL;
}
/**
* Returns the search base url
* @return search base url
* @since fanfoudroid 0.5.0
*/
public String getSearchBaseURL(){
return this.searchBaseURL;
}
/**
* Returns authenticating userid
* 注意:此userId不一定等同与饭否用户的user_id参数
* 它可能是任意一种当前用户所使用的ID类型(如邮箱,用户名等),
*
* @return userid
*/
public String getUserId() {
return http.getUserId();
}
/**
* Returns authenticating password
*
* @return password
*/
public String getPassword() {
return http.getPassword();
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, boolean authenticate) throws HttpException {
return get(url, null, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param authenticate if true, the request will be sent with BASIC authentication header
* @param name1 the name of the first parameter
* @param value1 the value of the first parameter
* @return the response
* @throws HttpException
*/
protected Response get(String url, String name1, String value1, boolean authenticate) throws HttpException {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add( new BasicNameValuePair(name1, HttpClient.encode(value1) ) );
return get(url, params, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param name1 the name of the first parameter
* @param value1 the value of the first parameter
* @param name2 the name of the second parameter
* @param value2 the value of the second parameter
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws HttpException {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair(name1, HttpClient.encode(value1)));
params.add(new BasicNameValuePair(name2, HttpClient.encode(value2)));
return get(url, params, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param params the request parameters
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, ArrayList<BasicNameValuePair> params, boolean authenticated) throws HttpException {
if (url.indexOf("?") == -1) {
url += "?source=" + CONSUMER_KEY;
} else if (url.indexOf("source") == -1) {
url += "&source=" + CONSUMER_KEY;
}
//以HTML格式获得数据,以便进一步处理
url += "&format=html";
if (null != params && params.size() > 0) {
url += "&" + HttpClient.encodeParameters(params);
}
return http.get(url, authenticated);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param params the request parameters
* @param paging controls pagination
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, ArrayList<BasicNameValuePair> params, Paging paging, boolean authenticate) throws HttpException {
if (null == params) {
params = new ArrayList<BasicNameValuePair>();
}
if (null != paging) {
if ("" != paging.getMaxId()) {
params.add(new BasicNameValuePair("max_id", String.valueOf(paging.getMaxId())));
}
if ("" != paging.getSinceId()) {
params.add(new BasicNameValuePair("since_id", String.valueOf(paging.getSinceId())));
}
if (-1 != paging.getPage()) {
params.add(new BasicNameValuePair("page", String.valueOf(paging.getPage())));
}
if (-1 != paging.getCount()) {
params.add(new BasicNameValuePair("count", String.valueOf(paging.getCount())));
}
return get(url, params, authenticate);
} else {
return get(url, params, authenticate);
}
}
/**
* 生成POST Parameters助手
* @param nameValuePair 参数(一个或多个)
* @return post parameters
*/
public ArrayList<BasicNameValuePair> createParams(BasicNameValuePair... nameValuePair ) {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (BasicNameValuePair param : nameValuePair) {
params.add(param);
}
return params;
}
/***************** API METHOD START *********************/
/* 搜索相关的方法 */
/**
* Returns tweets that match a specified query.
* <br>This method calls http://api.fanfou.com/users/search.format
* @param query - the search condition
* @return the result
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public QueryResult search(Query query) throws HttpException {
try{
return new QueryResult(get(searchBaseURL + "search/public_timeline.json", query.asPostParameters(), false), this);
}catch(HttpException te){
if(404 == te.getStatusCode()){
return new QueryResult(query);
}else{
throw te;
}
}
}
/**
* Returns the top ten topics that are currently trending on Weibo. The response includes the time of the request, the name of each trend.
* @return the result
* @throws HttpException
* @since fanfoudroid 0.5.0
*/
public Trends getTrends() throws HttpException {
return Trends.constructTrends(get(searchBaseURL + "trends.json", false));
}
private String toDateStr(Date date){
if(null == date){
date = new Date();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/* 消息相关的方法 */
/**
* Returns the 20 most recent statuses from non-protected users who have set a custom user icon.
* <br>This method calls http://api.fanfou.com/statuses/public_timeline.format
*
* @return list of statuses of the Public Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getPublicTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() +
"statuses/public_timeline.json", true));
}
public RateLimitStatus getRateLimitStatus()throws
HttpException {
return new RateLimitStatus(get(getBaseURL() +
"account/rate_limit_status.json", true),this);
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
* <br>This method calls http://api.fanfou.com/statuses/home_timeline.format
*
* @return list of the home Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getHomeTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", true));
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
* <br>This method calls http://api.fanfou.com/statuses/home_timeline.format
*
* @param paging controls pagination
* @return list of the home Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getHomeTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", null, paging, true));
}
/**
* Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends.
* It's also possible to request another user's friends_timeline via the id parameter below.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
*
* @return list of the Friends Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFriendsTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json", true));
}
/**
* Returns the 20 most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
*
* @param paging controls pagination
* @return list of the Friends Timeline
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFriendsTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true));
}
/**
* Returns friend time line by page and count.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
* @param page
* @param count
* @return
* @throws HttpException
*/
public List<Status> getFriendsTimeline(int page, int count) throws
HttpException {
Paging paging = new Paging(page, count);
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param id specifies the ID or screen name of the user for whom to return the user_timeline
* @param paging controls pagenation
* @return list of the user Timeline
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline(String id, Paging paging)
throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json",
null, paging, http.isAuthenticationEnabled()));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param id specifies the ID or screen name of the user for whom to return the user_timeline
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline(String id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json", http.isAuthenticationEnabled()));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, true));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param paging controls pagination
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getUserTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, null, paging, true));
}
public List<Status> getUserTimeline(int page, int count) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, null, new Paging(page, count), true));
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/mentions.format
*
* @return the 20 most recent replies
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getMentions() throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
null, true));
}
// by since_id
public List<Status> getMentions(String since_id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
"since_id", String.valueOf(since_id), true));
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/mentions.format
*
* @param paging controls pagination
* @return the 20 most recent replies
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getMentions(Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
null, paging, true));
}
/**
* Returns a single status, specified by the id parameter. The status's author will be returned inline.
* <br>This method calls http://api.fanfou.com/statuses/show/id.format
*
* @param id the numerical ID of the status you're trying to retrieve
* @return a single status
* @throws HttpException when Weibo service or network is unavailable. 可能因为“你没有通过这个用户的验证“,返回403
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status showStatus(String id) throws HttpException {
return new Status(get(getBaseURL() + "statuses/show/" + id + ".json", true));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>This method calls http://api.fanfou.com/statuses/update.format
*
* @param status the text of your status update
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status updateStatus(String status) throws HttpException{
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source))));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param latitude The location's latitude that this tweet refers to.
* @param longitude The location's longitude that this tweet refers to.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, double latitude, double longitude) throws HttpException, JSONException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("location", latitude + "," + longitude))));
}
/**
* Updates the user's status.
* 如果要使用inreplyToStatusId参数, 那么该status就必须得是@别人的.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, String inReplyToStatusId) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId))));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored.
* @param latitude The location's latitude that this tweet refers to.
* @param longitude The location's longitude that this tweet refers to.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, String inReplyToStatusId
, double latitude, double longitude) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("location", latitude + "," + longitude),
new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId))));
}
/**
* upload the photo.
* The text will be trimed if the length of the text is exceeding 160 characters.
* The image suport.
* <br>上传照片 http://api.fanfou.com/photos/upload.[json|xml]
*
* @param status the text of your status update
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status uploadPhoto(String status, File file) throws HttpException {
return new Status(http.httpRequest(getBaseURL() + "photos/upload.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source)),
file, true, HttpPost.METHOD_NAME));
}
public Status updateStatus(String status, File file) throws HttpException {
return uploadPhoto(status, file);
}
/**
* Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status.
* <br>删除消息 http://api.fanfou.com/statuses/destroy.[json|xml]
*
* @param statusId The ID of the status to destroy.
* @return the deleted status
* @throws HttpException when Weibo service or network is unavailable
* @since 1.0.5
*/
public Status destroyStatus(String statusId) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/destroy/" + statusId + ".json",
createParams(), true));
}
/**
* Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.
* <br>This method calls http://api.fanfou.com/users/show.format
*
* @param id (cann't be screenName the ID of the user for whom to request the detail
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public User showUser(String id) throws HttpException {
return new User(get(getBaseURL() + "users/show.json",
createParams(new BasicNameValuePair("id", id)), true));
}
/**
* Return a status of repost
* @param to_user_name repost status's user name
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @param new_status the new status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String to_user_name, String repost_status_id,
String repost_status_text, String new_status) throws HttpException {
StringBuilder sb = new StringBuilder();
sb.append(new_status);
sb.append(" ");
sb.append(R.string.pref_rt_prefix_default + ":@");
sb.append(to_user_name);
sb.append(" ");
sb.append(repost_status_text);
sb.append(" ");
String message = sb.toString();
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", message),
new BasicNameValuePair("repost_status_id", repost_status_id)), true));
}
/**
* Return a status of repost
* @param to_user_name repost status's user name
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @param new_status the new status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String new_status, String repost_status_id) throws HttpException
{
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", new_status),
new BasicNameValuePair("source", CONSUMER_KEY),
new BasicNameValuePair("repost_status_id", repost_status_id)), true));
}
/**
* Return a status of repost
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String repost_status_id, String new_status, boolean tmp) throws HttpException {
Status repost_to = showStatus(repost_status_id);
String to_user_name = repost_to.getUser().getName();
String repost_status_text = repost_to.getText();
return repost(to_user_name, repost_status_id, repost_status_text, new_status);
}
/* User Methods */
/**
* Returns the specified user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFriendsStatuses() throws HttpException {
return User.constructResult(get(getBaseURL() + "users/friends.json", true));
}
/**
* Returns the specified user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
* <br>分页每页显示100条
*
* @param paging controls pagination
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*
*/
public List<User> getFriendsStatuses(Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json", null,
paging, true));
}
/**
* Returns the user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFriendsStatuses(String id) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json",
createParams(new BasicNameValuePair("id", id)), false));
}
/**
* Returns the user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @param paging controls pagination (饭否API 默认返回 100 条/页)
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFriendsStatuses(String id, Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json",
createParams(new BasicNameValuePair("id", id)), paging, false));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFollowersStatuses() throws HttpException {
return User.constructResult(get(getBaseURL() + "statuses/followers.json", true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers.json", null
, paging, true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param id The ID (not screen name) of the user for whom to request a list of followers.
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(String id) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id + ".json", true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param id The ID or screen name of the user for whom to request a list of followers.
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(String id, Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id +
".json", null, paging, true));
}
/* 私信功能 */
/**
* Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.
* The text will be trimed if the length of the text is exceeding 140 characters.
* <br>This method calls http://api.fanfou.com/direct_messages/new.format
* <br>通过客户端只能给互相关注的人发私信
*
* @param id the ID of the user to whom send the direct message
* @param text String
* @return DirectMessage
* @throws HttpException when Weibo service or network is unavailable
@see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public DirectMessage sendDirectMessage(String id, String text) throws HttpException {
return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json",
createParams(new BasicNameValuePair("user", id),
new BasicNameValuePair("text", text))).asJSONObject());
}
//TODO: need be unit tested by in_reply_to_id.
/**
* Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.
* The text will be trimed if the length of the text is exceeding 140 characters.
* <br>通过客户端只能给互相关注的人发私信
*
* @param id
* @param text
* @param in_reply_to_id
* @return
* @throws HttpException
*/
public DirectMessage sendDirectMessage(String id, String text, String in_reply_to_id)
throws HttpException {
return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json",
createParams(new BasicNameValuePair("user", id),
new BasicNameValuePair("text", text),
new BasicNameValuePair("is_reply_to_id", in_reply_to_id))).asJSONObject());
}
/**
* Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.
* <br>This method calls http://api.fanfou.com/direct_messages/destroy/id.format
*
* @param id the ID of the direct message to destroy
* @return the deleted direct message
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public DirectMessage destroyDirectMessage(String id) throws
HttpException {
return new DirectMessage(http.post(getBaseURL() +
"direct_messages/destroy/" + id + ".json", true).asJSONObject());
}
/**
* Returns a list of the direct messages sent to the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getDirectMessages() throws HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() + "direct_messages.json", true));
}
/**
* Returns a list of the direct messages sent to the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages.format
*
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getDirectMessages(Paging paging) throws HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL()
+ "direct_messages.json", null, paging, true));
}
/**
* Returns a list of the direct messages sent by the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages/sent.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getSentDirectMessages() throws
HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() +
"direct_messages/sent.json", null, true));
}
/**
* Returns a list of the direct messages sent by the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages/sent.format
*
* @param paging controls pagination
* @return List 默认返回20条, 一次最多返回60条
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getSentDirectMessages(Paging paging) throws
HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() +
"direct_messages/sent.json", null, paging, true));
}
/* 收藏功能 */
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites() throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), true));
}
public List<Status> getFavorites(Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), paging, true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param page the number of page
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites(int page) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", "page", String.valueOf(page), true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param id the ID or screen name of the user for whom to request a list of favorite statuses
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites(String id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", createParams(), true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param id the ID or screen name of the user for whom to request a list of favorite statuses
* @param page the number of page
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFavorites(String id, int page) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", "page", String.valueOf(page), true));
}
public List<Status> getFavorites(String id, Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", null, paging, true));
}
/**
* Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.
*
* @param id the ID of the status to favorite
* @return Status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status createFavorite(String id) throws HttpException {
return new Status(http.post(getBaseURL() + "favorites/create/" + id + ".json", true));
}
/**
* Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful.
*
* @param id the ID of the status to un-favorite
* @return Status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status destroyFavorite(String id) throws HttpException {
return new Status(http.post(getBaseURL() + "favorites/destroy/" + id + ".json", true));
}
/**
* Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
* @param id String
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @deprecated 饭否该功能暂时关闭, 等待该功能开放.
*/
public User enableNotification(String id) throws HttpException {
return new User(http.post(getBaseURL() + "notifications/follow/" + id + ".json", true).asJSONObject());
}
/**
* Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
* @param id String
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否该功能暂时关闭, 等待该功能开放.
* @since fanfoudroid 0.5.0
*/
public User disableNotification(String id) throws HttpException {
return new User(http.post(getBaseURL() + "notifications/leave/" + id + ".json", true).asJSONObject());
}
/* 黑名单 */
/**
* Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful.
* @param id the ID or screen_name of the user to block
* @return the blocked user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public User createBlock(String id) throws HttpException {
return new User(http.post(getBaseURL() + "blocks/create/" + id + ".json", true).asJSONObject());
}
/**
* Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful.
* @param id the ID or screen_name of the user to block
* @return the unblocked user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public User destroyBlock(String id) throws HttpException {
return new User(http.post(getBaseURL() + "blocks/destroy/" + id + ".json", true).asJSONObject());
}
/**
* Tests if a friendship exists between two users.
* @param id The ID or screen_name of the potentially blocked user.
* @return if the authenticating user is blocking a target user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public boolean existsBlock(String id) throws HttpException {
try{
return -1 == get(getBaseURL() + "blocks/exists/" + id + ".json", true).
asString().indexOf("<error>You are not blocking this user.</error>");
}catch(HttpException te){
if(te.getStatusCode() == 404){
return false;
}
throw te;
}
}
/**
* Returns a list of user objects that the authenticating user is blocking.
* @return a list of user objects that the authenticating user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public List<User> getBlockingUsers() throws
HttpException {
return User.constructUsers(get(getBaseURL() +
"blocks/blocking.json", true));
}
/**
* Returns a list of user objects that the authenticating user is blocking.
* @param page the number of page
* @return a list of user objects that the authenticating user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public List<User> getBlockingUsers(int page) throws
HttpException {
return User.constructUsers(get(getBaseURL() +
"blocks/blocking.json?page=" + page, true));
}
/**
* Returns an array of numeric user ids the authenticating user is blocking.
* @return Returns an array of numeric user ids the authenticating user is blocking.
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public IDs getBlockingUsersIDs() throws HttpException {
return new IDs(get(getBaseURL() + "blocks/blocking/ids.json", true),this);
}
/* 好友关系方法 */
/**
* Tests if a friendship exists between two users.
*
* @param userA The ID or screen_name of the first user to test friendship for.
* @param userB The ID or screen_name of the second user to test friendship for.
* @return if a friendship exists between two users.
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public boolean existsFriendship(String userA, String userB) throws HttpException {
return -1 != get(getBaseURL() + "friendships/exists.json", "user_a", userA, "user_b", userB, true).
asString().indexOf("true");
}
/**
* Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User destroyFriendship(String id) throws HttpException {
return new User(http.post(getBaseURL() + "friendships/destroy/" + id + ".json", createParams(), true).asJSONObject());
}
/**
* Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
*
* @param id the ID or screen name of the user to be befriended
* @return the befriended user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User createFriendship(String id) throws HttpException {
return new User(http.post(getBaseURL() + "friendships/create/" + id + ".json", createParams(), true).asJSONObject());
}
/**
* Returns an array of numeric IDs for every user the specified user is followed by.
* @param userId Specifies the ID of the user for whom to return the followers list.
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return The ID or screen_name of the user to retrieve the friends ID list for.
* @throws HttpException when Weibo service or network is unavailable
* @since Weibo4J 2.0.10
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a>
*/
public IDs getFollowersIDs(String userId) throws HttpException {
return new IDs(get(getBaseURL() + "followers/ids.json?user_id=" + userId, true), this);
}
/**
* Returns an array of numeric IDs for every user the specified user is followed by.
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return The ID or screen_name of the user to retrieve the friends ID list for.
* @throws HttpException when Weibo service or network is unavailable
* @since Weibo4J 2.0.10
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a>
*/
public IDs getFollowersIDs() throws HttpException {
return new IDs(get(getBaseURL() + "followers/ids.json", true), this);
}
public List<com.ch_linghu.fanfoudroid.fanfou.User> getFollowersList(String userId,Paging paging) throws HttpException{
return User.constructUsers(get(getBaseURL() + "users/followers.json",
createParams(new BasicNameValuePair("id", userId)),paging, false));
}
public List<com.ch_linghu.fanfoudroid.fanfou.User> getFollowersList(String userId) throws HttpException{
return User.constructUsers(get(getBaseURL() + "users/followers.json",
createParams(new BasicNameValuePair("id", userId)), false));
}
/**
* Returns an array of numeric IDs for every user the authenticating user is following.
* @return an array of numeric IDs for every user the authenticating user is following
* @throws HttpException when Weibo service or network is unavailable
* @since androidroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public IDs getFriendsIDs() throws HttpException {
return getFriendsIDs(-1l);
}
/**
* Returns an array of numeric IDs for every user the authenticating user is following.
* <br/>饭否无cursor参数
*
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return an array of numeric IDs for every user the authenticating user is following
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public IDs getFriendsIDs(long cursor) throws HttpException {
return new IDs(get(getBaseURL() + "friends/ids.json?cursor=" + cursor, true), this);
}
/**
* 获取关注者id列表
* @param userId
* @return
* @throws HttpException
*/
public IDs getFriendsIDs(String userId) throws HttpException{
return new IDs(get(getBaseURL() + "friends/ids.json?id=" +userId , true), this);
}
/* 账户方法 */
/**
* Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid.
* 注意: 如果使用 错误的用户名/密码 多次登录后,饭否会锁IP
* 返回提示为“尝试次数过多,请去 http://fandou.com 登录“,且需输入验证码
*
* 登录成功返回 200 code
* 登录失败返回 401 code
* 使用HttpException的getStatusCode取得code
*
* @return user
* @since androidroid 0.5.0
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User verifyCredentials() throws HttpException {
return new User(get(getBaseURL() + "account/verify_credentials.json"
, true).asJSONObject());
}
/* Saved Searches Methods */
/**
* Returns the authenticated user's saved search queries.
* @return Returns an array of numeric user ids the authenticating user is blocking.
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public List<SavedSearch> getSavedSearches() throws HttpException {
return SavedSearch.constructSavedSearches(get(getBaseURL() + "saved_searches.json", true));
}
/**
* Retrieve the data for a saved search owned by the authenticating user specified by the given id.
* @param id The id of the saved search to be retrieved.
* @return the data for a saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch showSavedSearch(int id) throws HttpException {
return new SavedSearch(get(getBaseURL() + "saved_searches/show/" + id
+ ".json", true));
}
/**
* Retrieve the data for a saved search owned by the authenticating user specified by the given id.
* @return the data for a created saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch createSavedSearch(String query) throws HttpException {
return new SavedSearch(http.post(getBaseURL() + "saved_searches/create.json",
createParams(new BasicNameValuePair("query", query)), true));
}
/**
* Destroys a saved search for the authenticated user. The search specified by id must be owned by the authenticating user.
* @param id The id of the saved search to be deleted.
* @return the data for a destroyed saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch destroySavedSearch(int id) throws HttpException {
return new SavedSearch(http.post(getBaseURL() + "saved_searches/destroy/" + id
+ ".json", true));
}
/* Help Methods */
/**
* Returns the string "ok" in the requested format with a 200 OK HTTP status code.
* @return true if the API is working
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public boolean test() throws HttpException {
return -1 != get(getBaseURL() + "help/test.json", false).
asString().indexOf("ok");
}
/***************** API METHOD END *********************/
private SimpleDateFormat format = new SimpleDateFormat(
"EEE, d MMM yyyy HH:mm:ss z", Locale.US);
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Weibo weibo = (Weibo) o;
if (!baseURL.equals(weibo.baseURL)) return false;
if (!format.equals(weibo.format)) return false;
if (!http.equals(weibo.http)) return false;
if (!searchBaseURL.equals(weibo.searchBaseURL)) return false;
if (!source.equals(weibo.source)) return false;
return true;
}
@Override
public int hashCode() {
int result = http.hashCode();
result = 31 * result + baseURL.hashCode();
result = 31 * result + searchBaseURL.hashCode();
result = 31 * result + source.hashCode();
result = 31 * result + format.hashCode();
return result;
}
@Override
public String toString() {
return "Weibo{" +
"http=" + http +
", baseURL='" + baseURL + '\'' +
", searchBaseURL='" + searchBaseURL + '\'' +
", source='" + source + '\'' +
", format=" + format +
'}';
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/Weibo.java | Java | asf20 | 61,339 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing one single status of a user.
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Status extends WeiboResponse implements java.io.Serializable {
private static final long serialVersionUID = 1608000492860584608L;
private Date createdAt;
private String id;
private String text;
private String source;
private boolean isTruncated;
private String inReplyToStatusId;
private String inReplyToUserId;
private boolean isFavorited;
private String inReplyToScreenName;
private double latitude = -1;
private double longitude = -1;
private String thumbnail_pic;
private String bmiddle_pic;
private String original_pic;
private String photo_url;
private RetweetDetails retweetDetails;
private User user = null;
/*package*/Status(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(res, elem, weibo);
}
/*package*/Status(Response res, Element elem, Weibo weibo) throws
HttpException {
super(res);
init(res, elem, weibo);
}
Status(Response res)throws HttpException{
super(res);
JSONObject json=res.asJSONObject();
try {
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
isFavorited = getBoolean("favorited", json);
// System.out.println("json photo" + json.getJSONObject("photo"));
if(!json.isNull("photo")) {
// System.out.println("not null" + json.getJSONObject("photo"));
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
// System.out.println("Null");
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
if(!json.isNull("user"))
user = new User(json.getJSONObject("user"));
inReplyToScreenName=json.getString("in_reply_to_screen_name");
if(!json.isNull("retweetDetails")){
retweetDetails = new RetweetDetails(json.getJSONObject("retweetDetails"));
}
} catch (JSONException je) {
throw new HttpException(je.getMessage() + ":" + json.toString(), je);
}
}
/* modify by sycheng add some field*/
public Status(JSONObject json)throws HttpException, JSONException{
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
isFavorited = getBoolean("favorited", json);
isTruncated=getBoolean("truncated", json);
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
inReplyToScreenName=json.getString("in_reply_to_screen_name");
if(!json.isNull("photo")) {
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
user = new User(json.getJSONObject("user"));
}
public Status(String str) throws HttpException, JSONException {
// StatusStream uses this constructor
super();
JSONObject json = new JSONObject(str);
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
isFavorited = getBoolean("favorited", json);
if(!json.isNull("photo")) {
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
user = new User(json.getJSONObject("user"));
}
private void init(Response res, Element elem, Weibo weibo) throws
HttpException {
ensureRootNodeNameIs("status", elem);
user = new User(res, (Element) elem.getElementsByTagName("user").item(0)
, weibo);
id = getChildString("id", elem);
text = getChildText("text", elem);
source = getChildText("source", elem);
createdAt = getChildDate("created_at", elem);
isTruncated = getChildBoolean("truncated", elem);
inReplyToStatusId = getChildString("in_reply_to_status_id", elem);
inReplyToUserId = getChildString("in_reply_to_user_id", elem);
isFavorited = getChildBoolean("favorited", elem);
inReplyToScreenName = getChildText("in_reply_to_screen_name", elem);
NodeList georssPoint = elem.getElementsByTagName("georss:point");
if(1 == georssPoint.getLength()){
String[] point = georssPoint.item(0).getFirstChild().getNodeValue().split(" ");
if(!"null".equals(point[0]))
latitude = Double.parseDouble(point[0]);
if(!"null".equals(point[1]))
longitude = Double.parseDouble(point[1]);
}
NodeList retweetDetailsNode = elem.getElementsByTagName("retweet_details");
if(1 == retweetDetailsNode.getLength()){
retweetDetails = new RetweetDetails(res,(Element)retweetDetailsNode.item(0),weibo);
}
}
/**
* Return the created_at
*
* @return created_at
* @since Weibo4J 1.1.0
*/
public Date getCreatedAt() {
return this.createdAt;
}
/**
* Returns the id of the status
*
* @return the id
*/
public String getId() {
return this.id;
}
/**
* Returns the text of the status
*
* @return the text
*/
public String getText() {
return this.text;
}
/**
* Returns the source
*
* @return the source
* @since Weibo4J 1.0.4
*/
public String getSource() {
return this.source;
}
/**
* Test if the status is truncated
*
* @return true if truncated
* @since Weibo4J 1.0.4
*/
public boolean isTruncated() {
return isTruncated;
}
/**
* Returns the in_reply_tostatus_id
*
* @return the in_reply_tostatus_id
* @since Weibo4J 1.0.4
*/
public String getInReplyToStatusId() {
return inReplyToStatusId;
}
/**
* Returns the in_reply_user_id
*
* @return the in_reply_tostatus_id
* @since Weibo4J 1.0.4
*/
public String getInReplyToUserId() {
return inReplyToUserId;
}
/**
* Returns the in_reply_to_screen_name
*
* @return the in_in_reply_to_screen_name
* @since Weibo4J 2.0.4
*/
public String getInReplyToScreenName() {
return inReplyToScreenName;
}
/**
* returns The location's latitude that this tweet refers to.
*
* @since Weibo4J 2.0.10
*/
public double getLatitude() {
return latitude;
}
/**
* returns The location's longitude that this tweet refers to.
*
* @since Weibo4J 2.0.10
*/
public double getLongitude() {
return longitude;
}
/**
* Test if the status is favorited
*
* @return true if favorited
* @since Weibo4J 1.0.4
*/
public boolean isFavorited() {
return isFavorited;
}
public String getThumbnail_pic() {
return thumbnail_pic;
}
public String getBmiddle_pic() {
return bmiddle_pic;
}
public String getOriginal_pic() {
return original_pic;
}
/**
* Return the user
*
* @return the user
*/
public User getUser() {
return user;
}
// TODO: 等合并Tweet, Status
public int getType() {
return -1111111;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean isRetweet(){
return null != retweetDetails;
}
/**
*
* @since Weibo4J 2.0.10
*/
public RetweetDetails getRetweetDetails() {
return retweetDetails;
}
/*package*/
static List<Status> constructStatuses(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<Status>(0);
} else {
try {
ensureRootNodeNameIs("statuses", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"status");
int size = list.getLength();
List<Status> statuses = new ArrayList<Status>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
statuses.add(new Status(res, status, weibo));
}
return statuses;
} catch (HttpException te) {
ensureRootNodeNameIs("nil-classes", doc);
return new ArrayList<Status>(0);
}
}
}
/* modify by sycheng add json call method */
/* package */
static List<Status> constructStatuses(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<Status> statuses = new ArrayList<Status>(size);
for (int i = 0; i < size; i++) {
statuses.add(new Status(list.getJSONObject(i)));
}
return statuses;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
// return obj instanceof Status && ((Status) obj).id == this.id;
return obj instanceof Status && this.id.equals(((Status) obj).id);
}
@Override
public String toString() {
return "Status{" +
"createdAt=" + createdAt +
", id=" + id +
", text='" + text + '\'' +
", source='" + source + '\'' +
", isTruncated=" + isTruncated +
", inReplyToStatusId=" + inReplyToStatusId +
", inReplyToUserId=" + inReplyToUserId +
", isFavorited=" + isFavorited +
", thumbnail_pic=" + thumbnail_pic +
", bmiddle_pic=" + bmiddle_pic +
", original_pic=" + original_pic +
", inReplyToScreenName='" + inReplyToScreenName + '\'' +
", latitude=" + latitude +
", longitude=" + longitude +
", retweetDetails=" + retweetDetails +
", user=" + user +
'}';
}
public boolean isEmpty() {
return (null == id);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/Status.java | Java | asf20 | 13,518 |
package com.ch_linghu.fanfoudroid.fanfou;
/**
* An exception class that will be thrown when WeiboAPI calls are failed.<br>
* In case the Fanfou server returned HTTP error code, you can get the HTTP status code using getStatusCode() method.
*/
public class WeiboException extends Exception {
private int statusCode = -1;
private static final long serialVersionUID = -2623309261327598087L;
public WeiboException(String msg) {
super(msg);
}
public WeiboException(Exception cause) {
super(cause);
}
public WeiboException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public WeiboException(String msg, Exception cause) {
super(msg, cause);
}
public WeiboException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/WeiboException.java | Java | asf20 | 982 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing a Saved Search
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.8
*/
public class SavedSearch extends WeiboResponse {
private Date createdAt;
private String query;
private int position;
private String name;
private int id;
private static final long serialVersionUID = 3083819860391598212L;
/*package*/ SavedSearch(Response res) throws HttpException {
super(res);
init(res.asJSONObject());
}
/*package*/ SavedSearch(Response res, JSONObject json) throws HttpException {
super(res);
init(json);
}
/*package*/ SavedSearch(JSONObject savedSearch) throws HttpException {
init(savedSearch);
}
/*package*/ static List<SavedSearch> constructSavedSearches(Response res) throws HttpException {
JSONArray json = res.asJSONArray();
List<SavedSearch> savedSearches;
try {
savedSearches = new ArrayList<SavedSearch>(json.length());
for(int i=0;i<json.length();i++){
savedSearches.add(new SavedSearch(res,json.getJSONObject(i)));
}
return savedSearches;
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
private void init(JSONObject savedSearch) throws HttpException {
try {
createdAt = parseDate(savedSearch.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
query = getString("query", savedSearch, true);
name = getString("name", savedSearch, true);
id = getInt("id", savedSearch);
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + savedSearch.toString(), jsone);
}
}
public Date getCreatedAt() {
return createdAt;
}
public String getQuery() {
return query;
}
public int getPosition() {
return position;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SavedSearch)) return false;
SavedSearch that = (SavedSearch) o;
if (id != that.id) return false;
if (position != that.position) return false;
if (!createdAt.equals(that.createdAt)) return false;
if (!name.equals(that.name)) return false;
if (!query.equals(that.query)) return false;
return true;
}
@Override
public int hashCode() {
int result = createdAt.hashCode();
result = 31 * result + query.hashCode();
result = 31 * result + position;
result = 31 * result + name.hashCode();
result = 31 * result + id;
return result;
}
@Override
public String toString() {
return "SavedSearch{" +
"createdAt=" + createdAt +
", query='" + query + '\'' +
", position=" + position +
", name='" + name + '\'' +
", id=" + id +
'}';
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/SavedSearch.java | Java | asf20 | 5,041 |
/*
Copyright (c) 2007-2009
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import org.apache.http.message.BasicNameValuePair;
/**
* A data class represents search query.
*/
public class Query {
private String query = null;
private String lang = null;
private int rpp = -1;
private int page = -1;
private long sinceId = -1;
private String maxId = null;
private String geocode = null;
public Query(){
}
public Query(String query){
this.query = query;
}
public String getQuery() {
return query;
}
/**
* Sets the query string
* @param query - the query string
*/
public void setQuery(String query) {
this.query = query;
}
public String getLang() {
return lang;
}
/**
* restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
* @param lang an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
*/
public void setLang(String lang) {
this.lang = lang;
}
public int getRpp() {
return rpp;
}
/**
* sets the number of tweets to return per page, up to a max of 100
* @param rpp the number of tweets to return per page
*/
public void setRpp(int rpp) {
this.rpp = rpp;
}
public int getPage() {
return page;
}
/**
* sets the page number (starting at 1) to return, up to a max of roughly 1500 results
* @param page - the page number (starting at 1) to return
*/
public void setPage(int page) {
this.page = page;
}
public long getSinceId() {
return sinceId;
}
/**
* returns tweets with status ids greater than the given id.
* @param sinceId - returns tweets with status ids greater than the given id
*/
public void setSinceId(long sinceId) {
this.sinceId = sinceId;
}
public String getMaxId() {
return maxId;
}
/**
* returns tweets with status ids less than the given id.
* @param maxId - returns tweets with status ids less than the given id
*/
public void setMaxId(String maxId) {
this.maxId = maxId;
}
public String getGeocode() {
return geocode;
}
public static final String MILES = "mi";
public static final String KILOMETERS = "km";
/**
* returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Weibo profile
* @param latitude latitude
* @param longtitude longtitude
* @param radius radius
* @param unit Query.MILES or Query.KILOMETERS
*/
public void setGeoCode(double latitude, double longtitude, double radius
, String unit) {
this.geocode = latitude + "," + longtitude + "," + radius + unit;
}
public ArrayList<BasicNameValuePair> asPostParameters(){
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
appendParameter("q", query, params);
appendParameter("lang", lang, params);
appendParameter("page", page, params);
appendParameter("since_id",sinceId , params);
appendParameter("max_id", maxId, params);
appendParameter("geocode", geocode, params);
return params;
}
private void appendParameter(String name, String value, ArrayList<BasicNameValuePair> params) {
if (null != value) {
params.add(new BasicNameValuePair(name, value));
}
}
private void appendParameter(String name, long value, ArrayList<BasicNameValuePair> params) {
if (0 <= value) {
params.add(new BasicNameValuePair(name, value + ""));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Query query1 = (Query) o;
if (page != query1.page) return false;
if (rpp != query1.rpp) return false;
if (sinceId != query1.sinceId) return false;
if (geocode != null ? !geocode.equals(query1.geocode) : query1.geocode != null)
return false;
if (lang != null ? !lang.equals(query1.lang) : query1.lang != null)
return false;
if (query != null ? !query.equals(query1.query) : query1.query != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = query != null ? query.hashCode() : 0;
result = 31 * result + (lang != null ? lang.hashCode() : 0);
result = 31 * result + rpp;
result = 31 * result + page;
result = 31 * result + (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (geocode != null ? geocode.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Query{" +
"query='" + query + '\'' +
", lang='" + lang + '\'' +
", rpp=" + rpp +
", page=" + page +
", sinceId=" + sinceId +
", geocode='" + geocode + '\'' +
'}';
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/Query.java | Java | asf20 | 6,708 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HTMLEntity;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Super class of Weibo Response objects.
*
* @see weibo4j.DirectMessage
* @see weibo4j.Status
* @see weibo4j.User
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class WeiboResponse implements java.io.Serializable {
private static Map<String,SimpleDateFormat> formatMap = new HashMap<String,SimpleDateFormat>();
private static final long serialVersionUID = 3519962197957449562L;
private transient int rateLimitLimit = -1;
private transient int rateLimitRemaining = -1;
private transient long rateLimitReset = -1;
public WeiboResponse() {
}
public WeiboResponse(Response res) {
}
protected static void ensureRootNodeNameIs(String rootName, Element elem) throws HttpException {
if (!rootName.equals(elem.getNodeName())) {
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
}
}
protected static void ensureRootNodeNameIs(String[] rootNames, Element elem) throws HttpException {
String actualRootName = elem.getNodeName();
for (String rootName : rootNames) {
if (rootName.equals(actualRootName)) {
return;
}
}
String expected = "";
for (int i = 0; i < rootNames.length; i++) {
if (i != 0) {
expected += " or ";
}
expected += rootNames[i];
}
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + expected + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
}
protected static void ensureRootNodeNameIs(String rootName, Document doc) throws HttpException {
Element elem = doc.getDocumentElement();
if (!rootName.equals(elem.getNodeName())) {
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/");
}
}
protected static boolean isRootNodeNilClasses(Document doc) {
String root = doc.getDocumentElement().getNodeName();
return "nil-classes".equals(root) || "nilclasses".equals(root);
}
protected static String getChildText( String str, Element elem ) {
return HTMLEntity.unescape(getTextContent(str,elem));
}
protected static String getTextContent(String str, Element elem){
NodeList nodelist = elem.getElementsByTagName(str);
if (nodelist.getLength() > 0) {
Node node = nodelist.item(0).getFirstChild();
if (null != node) {
String nodeValue = node.getNodeValue();
return null != nodeValue ? nodeValue : "";
}
}
return "";
}
/*modify by sycheng add "".equals(str) */
protected static int getChildInt(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return -1;
} else {
return Integer.valueOf(str2);
}
}
/*modify by sycheng add "".equals(str) */
protected static String getChildString(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return "";
} else {
return String.valueOf(str2);
}
}
protected static long getChildLong(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return -1;
} else {
return Long.valueOf(str2);
}
}
protected static String getString(String name, JSONObject json, boolean decode) {
String returnValue = null;
try {
returnValue = json.getString(name);
if (decode) {
try {
returnValue = URLDecoder.decode(returnValue, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
}
} catch (JSONException ignore) {
// refresh_url could be missing
}
return returnValue;
}
protected static boolean getChildBoolean(String str, Element elem) {
String value = getTextContent(str, elem);
return Boolean.valueOf(value);
}
protected static Date getChildDate(String str, Element elem) throws HttpException {
return getChildDate(str, elem, "EEE MMM d HH:mm:ss z yyyy");
}
protected static Date getChildDate(String str, Element elem, String format) throws HttpException {
return parseDate(getChildText(str, elem),format);
}
protected static Date parseDate(String str, String format) throws HttpException{
if(str==null||"".equals(str)){
return null;
}
SimpleDateFormat sdf = formatMap.get(format);
if (null == sdf) {
sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
formatMap.put(format, sdf);
}
try {
synchronized(sdf){
// SimpleDateFormat is not thread safe
return sdf.parse(str);
}
} catch (ParseException pe) {
throw new HttpException("Unexpected format(" + str + ") returned from sina.com.cn");
}
}
protected static int getInt(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Integer.parseInt(str);
}
protected static String getString(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return "";
}
return String.valueOf(str);
}
protected static long getLong(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Long.parseLong(str);
}
protected static boolean getBoolean(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return false;
}
return Boolean.valueOf(str);
}
public int getRateLimitLimit() {
return rateLimitLimit;
}
public int getRateLimitRemaining() {
return rateLimitRemaining;
}
public long getRateLimitReset() {
return rateLimitReset;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/WeiboResponse.java | Java | asf20 | 9,049 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.database.Cursor;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Basic user information element
*/
public class User extends WeiboResponse implements java.io.Serializable {
static final String[] POSSIBLE_ROOT_NAMES = new String[]{"user", "sender", "recipient", "retweeting_user"};
private Weibo weibo;
private String id;
private String name;
private String screenName;
private String location;
private String description;
private String birthday;
private String gender;
private String profileImageUrl;
private String url;
private boolean isProtected;
private int followersCount;
private Date statusCreatedAt;
private String statusId = "";
private String statusText = null;
private String statusSource = null;
private boolean statusTruncated = false;
private String statusInReplyToStatusId = "";
private String statusInReplyToUserId = "";
private boolean statusFavorited = false;
private String statusInReplyToScreenName = null;
private String profileBackgroundColor;
private String profileTextColor;
private String profileLinkColor;
private String profileSidebarFillColor;
private String profileSidebarBorderColor;
private int friendsCount;
private Date createdAt;
private int favouritesCount;
private int utcOffset;
private String timeZone;
private String profileBackgroundImageUrl;
private String profileBackgroundTile;
private boolean following;
private boolean notificationEnabled;
private int statusesCount;
private boolean geoEnabled;
private boolean verified;
private static final long serialVersionUID = -6345893237975349030L;
/*package*/User(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(elem, weibo);
}
/*package*/public User(Response res, Element elem, Weibo weibo) throws HttpException {
super(res);
init(elem, weibo);
}
/*package*/public User(JSONObject json) throws HttpException {
super();
init(json);
}
/*package*/User(Response res) throws HttpException {
super();
init(res.asJSONObject());
}
User(){
}
private void init(JSONObject json) throws HttpException {
try {
id = json.getString("id");
name = json.getString("name");
screenName = json.getString("screen_name");
location = json.getString("location");
gender = json.getString("gender");
birthday = json.getString("birthday");
description = json.getString("description");
profileImageUrl = json.getString("profile_image_url");
url = json.getString("url");
isProtected = json.getBoolean("protected");
followersCount = json.getInt("followers_count");
profileBackgroundColor = json.getString("profile_background_color");
profileTextColor = json.getString("profile_text_color");
profileLinkColor = json.getString("profile_link_color");
profileSidebarFillColor = json.getString("profile_sidebar_fill_color");
profileSidebarBorderColor = json.getString("profile_sidebar_border_color");
friendsCount = json.getInt("friends_count");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
favouritesCount = json.getInt("favourites_count");
utcOffset = getInt("utc_offset", json);
// timeZone = json.getString("time_zone");
profileBackgroundImageUrl = json.getString("profile_background_image_url");
profileBackgroundTile = json.getString("profile_background_tile");
following = getBoolean("following", json);
notificationEnabled = getBoolean("notifications", json);
statusesCount = json.getInt("statuses_count");
if (!json.isNull("status")) {
JSONObject status = json.getJSONObject("status");
statusCreatedAt = parseDate(status.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
statusId = status.getString("id");
statusText = status.getString("text");
statusSource = status.getString("source");
statusTruncated = status.getBoolean("truncated");
// statusInReplyToStatusId = status.getString("in_reply_to_status_id");
statusInReplyToStatusId = status.getString("in_reply_to_lastmsg_id"); // 饭否不知为什么把这个参数的名称改了
statusInReplyToUserId = status.getString("in_reply_to_user_id");
statusFavorited = status.getBoolean("favorited");
statusInReplyToScreenName = status.getString("in_reply_to_screen_name");
}
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
private void init(Element elem, Weibo weibo) throws HttpException {
this.weibo = weibo;
ensureRootNodeNameIs(POSSIBLE_ROOT_NAMES, elem);
id = getChildString("id", elem);
name = getChildText("name", elem);
screenName = getChildText("screen_name", elem);
location = getChildText("location", elem);
description = getChildText("description", elem);
profileImageUrl = getChildText("profile_image_url", elem);
url = getChildText("url", elem);
isProtected = getChildBoolean("protected", elem);
followersCount = getChildInt("followers_count", elem);
profileBackgroundColor = getChildText("profile_background_color", elem);
profileTextColor = getChildText("profile_text_color", elem);
profileLinkColor = getChildText("profile_link_color", elem);
profileSidebarFillColor = getChildText("profile_sidebar_fill_color", elem);
profileSidebarBorderColor = getChildText("profile_sidebar_border_color", elem);
friendsCount = getChildInt("friends_count", elem);
createdAt = getChildDate("created_at", elem);
favouritesCount = getChildInt("favourites_count", elem);
utcOffset = getChildInt("utc_offset", elem);
// timeZone = getChildText("time_zone", elem);
profileBackgroundImageUrl = getChildText("profile_background_image_url", elem);
profileBackgroundTile = getChildText("profile_background_tile", elem);
following = getChildBoolean("following", elem);
notificationEnabled = getChildBoolean("notifications", elem);
statusesCount = getChildInt("statuses_count", elem);
geoEnabled = getChildBoolean("geo_enabled", elem);
verified = getChildBoolean("verified", elem);
NodeList statuses = elem.getElementsByTagName("status");
if (statuses.getLength() != 0) {
Element status = (Element) statuses.item(0);
statusCreatedAt = getChildDate("created_at", status);
statusId = getChildString("id", status);
statusText = getChildText("text", status);
statusSource = getChildText("source", status);
statusTruncated = getChildBoolean("truncated", status);
statusInReplyToStatusId = getChildString("in_reply_to_status_id", status);
statusInReplyToUserId = getChildString("in_reply_to_user_id", status);
statusFavorited = getChildBoolean("favorited", status);
statusInReplyToScreenName = getChildText("in_reply_to_screen_name", status);
}
}
/**
* Returns the id of the user
*
* @return the id of the user
*/
public String getId() {
return id;
}
/**
* Returns the name of the user
*
* @return the name of the user
*/
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getBirthday() {
return birthday;
}
/**
* Returns the screen name of the user
*
* @return the screen name of the user
*/
public String getScreenName() {
return screenName;
}
/**
* Returns the location of the user
*
* @return the location of the user
*/
public String getLocation() {
return location;
}
/**
* Returns the description of the user
*
* @return the description of the user
*/
public String getDescription() {
return description;
}
/**
* Returns the profile image url of the user
*
* @return the profile image url of the user
*/
public URL getProfileImageURL() {
try {
return new URL(profileImageUrl);
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Returns the url of the user
*
* @return the url of the user
*/
public URL getURL() {
try {
return new URL(url);
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Test if the user status is protected
*
* @return true if the user status is protected
*/
public boolean isProtected() {
return isProtected;
}
/**
* Returns the number of followers
*
* @return the number of followers
* @since Weibo4J 1.0.4
*/
public int getFollowersCount() {
return followersCount;
}
//TODO: uncomment
// public DirectMessage sendDirectMessage(String text) throws WeiboException {
// return weibo.sendDirectMessage(this.getName(), text);
// }
public static List<User> constructUsers(Response res, Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<User>(0);
} else {
try {
ensureRootNodeNameIs("users", doc);
// NodeList list = doc.getDocumentElement().getElementsByTagName(
// "user");
// int size = list.getLength();
// List<User> users = new ArrayList<User>(size);
// for (int i = 0; i < size; i++) {
// users.add(new User(res, (Element) list.item(i), weibo));
// }
//去除掉嵌套的bug
NodeList list=doc.getDocumentElement().getChildNodes();
List<User> users = new ArrayList<User>(list.getLength());
Node node;
for(int i=0;i<list.getLength();i++){
node=list.item(i);
if(node.getNodeName().equals("user")){
users.add(new User(res, (Element) node, weibo));
}
}
return users;
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new ArrayList<User>(0);
} else {
throw te;
}
}
}
}
public static UserWapper constructWapperUsers(Response res, Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
} else {
try {
ensureRootNodeNameIs("users_list", doc);
Element root = doc.getDocumentElement();
NodeList user = root.getElementsByTagName("users");
int length = user.getLength();
if (length == 0) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
}
//
Element listsRoot = (Element) user.item(0);
NodeList list=listsRoot.getChildNodes();
List<User> users = new ArrayList<User>(list.getLength());
Node node;
for(int i=0;i<list.getLength();i++){
node=list.item(i);
if(node.getNodeName().equals("user")){
users.add(new User(res, (Element) node, weibo));
}
}
//
long previousCursor = getChildLong("previous_curosr", root);
long nextCursor = getChildLong("next_curosr", root);
if (nextCursor == -1) { // 兼容不同标签名称
nextCursor = getChildLong("nextCurosr", root);
}
return new UserWapper(users, previousCursor, nextCursor);
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
} else {
throw te;
}
}
}
}
public static List<User> constructUsers(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(list.getJSONObject(i)));
}
return users;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
/**
*
* @param res
* @return
* @throws HttpException
*/
public static UserWapper constructWapperUsers(Response res) throws HttpException {
JSONObject jsonUsers = res.asJSONObject(); //asJSONArray();
try {
JSONArray user = jsonUsers.getJSONArray("users");
int size = user.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(user.getJSONObject(i)));
}
long previousCursor = jsonUsers.getLong("previous_curosr");
long nextCursor = jsonUsers.getLong("next_cursor");
if (nextCursor == -1) { // 兼容不同标签名称
nextCursor = jsonUsers.getLong("nextCursor");
}
return new UserWapper(users, previousCursor, nextCursor);
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
/**
* @param res
* @return
* @throws HttpException
*/
static List<User> constructResult(Response res) throws HttpException {
JSONArray list = res.asJSONArray();
try {
int size = list.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(list.getJSONObject(i)));
}
return users;
} catch (JSONException e) {
}
return null;
}
/**
* @return created_at or null if the user is protected
* @since Weibo4J 1.1.0
*/
public Date getStatusCreatedAt() {
return statusCreatedAt;
}
/**
*
* @return status id or -1 if the user is protected
*/
public String getStatusId() {
return statusId;
}
/**
*
* @return status text or null if the user is protected
*/
public String getStatusText() {
return statusText;
}
/**
*
* @return source or null if the user is protected
* @since 1.1.4
*/
public String getStatusSource() {
return statusSource;
}
/**
*
* @return truncated or false if the user is protected
* @since 1.1.4
*/
public boolean isStatusTruncated() {
return statusTruncated;
}
/**
*
* @return in_reply_to_status_id or -1 if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToStatusId() {
return statusInReplyToStatusId;
}
/**
*
* @return in_reply_to_user_id or -1 if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToUserId() {
return statusInReplyToUserId;
}
/**
*
* @return favorited or false if the user is protected
* @since 1.1.4
*/
public boolean isStatusFavorited() {
return statusFavorited;
}
/**
*
* @return in_reply_to_screen_name or null if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToScreenName() {
return "" != statusInReplyToUserId ? statusInReplyToScreenName : null;
}
public String getProfileBackgroundColor() {
return profileBackgroundColor;
}
public String getProfileTextColor() {
return profileTextColor;
}
public String getProfileLinkColor() {
return profileLinkColor;
}
public String getProfileSidebarFillColor() {
return profileSidebarFillColor;
}
public String getProfileSidebarBorderColor() {
return profileSidebarBorderColor;
}
public int getFriendsCount() {
return friendsCount;
}
public Date getCreatedAt() {
return createdAt;
}
public int getFavouritesCount() {
return favouritesCount;
}
public int getUtcOffset() {
return utcOffset;
}
public String getTimeZone() {
return timeZone;
}
public String getProfileBackgroundImageUrl() {
return profileBackgroundImageUrl;
}
public String getProfileBackgroundTile() {
return profileBackgroundTile;
}
/**
*
*/
public boolean isFollowing() {
return following;
}
/**
* @deprecated use isNotificationsEnabled() instead
*/
public boolean isNotifications() {
return notificationEnabled;
}
/**
*
* @since Weibo4J 2.0.1
*/
public boolean isNotificationEnabled() {
return notificationEnabled;
}
public int getStatusesCount() {
return statusesCount;
}
/**
* @return the user is enabling geo location
* @since Weibo4J 2.0.10
*/
public boolean isGeoEnabled() {
return geoEnabled;
}
/**
* @return returns true if the user is a verified celebrity
* @since Weibo4J 2.0.10
*/
public boolean isVerified() {
return verified;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
return obj instanceof User && ((User) obj).id.equals(this.id);
}
@Override
public String toString() {
return "User{" +
"weibo=" + weibo +
", id=" + id +
", name='" + name + '\'' +
", screenName='" + screenName + '\'' +
", location='" + location + '\'' +
", description='" + description + '\'' +
", profileImageUrl='" + profileImageUrl + '\'' +
", url='" + url + '\'' +
", isProtected=" + isProtected +
", followersCount=" + followersCount +
", statusCreatedAt=" + statusCreatedAt +
", statusId=" + statusId +
", statusText='" + statusText + '\'' +
", statusSource='" + statusSource + '\'' +
", statusTruncated=" + statusTruncated +
", statusInReplyToStatusId=" + statusInReplyToStatusId +
", statusInReplyToUserId=" + statusInReplyToUserId +
", statusFavorited=" + statusFavorited +
", statusInReplyToScreenName='" + statusInReplyToScreenName + '\'' +
", profileBackgroundColor='" + profileBackgroundColor + '\'' +
", profileTextColor='" + profileTextColor + '\'' +
", profileLinkColor='" + profileLinkColor + '\'' +
", profileSidebarFillColor='" + profileSidebarFillColor + '\'' +
", profileSidebarBorderColor='" + profileSidebarBorderColor + '\'' +
", friendsCount=" + friendsCount +
", createdAt=" + createdAt +
", favouritesCount=" + favouritesCount +
", utcOffset=" + utcOffset +
// ", timeZone='" + timeZone + '\'' +
", profileBackgroundImageUrl='" + profileBackgroundImageUrl + '\'' +
", profileBackgroundTile='" + profileBackgroundTile + '\'' +
", following=" + following +
", notificationEnabled=" + notificationEnabled +
", statusesCount=" + statusesCount +
", geoEnabled=" + geoEnabled +
", verified=" + verified +
'}';
}
//TODO:增加从游标解析User的方法,用于和data里User转换一条数据
public static User parseUser(Cursor cursor){
if (null == cursor || 0 == cursor.getCount()||cursor.getCount()>1) {
Log.w("User.ParseUser", "Cann't parse Cursor, bacause cursor is null or empty.");
}
cursor.moveToFirst();
User u=new User();
u.id = cursor.getString(cursor.getColumnIndex(UserInfoTable._ID));
u.name = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_NAME));
u.screenName = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_SCREEN_NAME));
u.location = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_LOCALTION));
u.description = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_DESCRIPTION));
u.profileImageUrl = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_PROFILE_IMAGE_URL));
u.url = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_URL));
u.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_PROTECTED))) ? false : true;
u.followersCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWERS_COUNT));
u.friendsCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FRIENDS_COUNT));
u.favouritesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FAVORITES_COUNT));
u.statusesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_STATUSES_COUNT));
u.following = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWING))) ? false : true;
try {
String createAtStr=cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT));
if(createAtStr!=null){
u.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(createAtStr);
}
} catch (ParseException e) {
Log.w("User", "Invalid created at data.");
}
return u;
}
public com.ch_linghu.fanfoudroid.data.User parseUser(){
com.ch_linghu.fanfoudroid.data.User user=new com.ch_linghu.fanfoudroid.data.User();
user.id=this.id;
user.name=this.name;
user.screenName=this.screenName;
user.location=this.location;
user.description=this.description;
user.profileImageUrl=this.profileImageUrl;
user.url=this.url;
user.isProtected=this.isProtected;
user.followersCount=this.followersCount;
user.friendsCount=this.friendsCount;
user.favoritesCount=this.favouritesCount;
user.statusesCount=this.statusesCount;
user.isFollowing=this.following;
user.createdAt = this.createdAt;
return user;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/User.java | Java | asf20 | 25,389 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import org.json.JSONException;
import org.json.JSONObject;
/**
* A data class representing Treand.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.2
*/
public class Trend implements java.io.Serializable{
private String name;
private String url = null;
private String query = null;
private static final long serialVersionUID = 1925956704460743946L;
public Trend(JSONObject json) throws JSONException {
this.name = json.getString("name");
if (!json.isNull("url")) {
this.url = json.getString("url");
}
if (!json.isNull("query")) {
this.query = json.getString("query");
}
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public String getQuery() {
return query;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Trend)) return false;
Trend trend = (Trend) o;
if (!name.equals(trend.name)) return false;
if (query != null ? !query.equals(trend.query) : trend.query != null)
return false;
if (url != null ? !url.equals(trend.url) : trend.url != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (url != null ? url.hashCode() : 0);
result = 31 * result + (query != null ? query.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Trend{" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", query='" + query + '\'' +
'}';
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/Trend.java | Java | asf20 | 3,323 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing one single retweet details.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.10
*/
public class RetweetDetails extends WeiboResponse implements
java.io.Serializable {
private long retweetId;
private Date retweetedAt;
private User retweetingUser;
static final long serialVersionUID = 1957982268696560598L;
public RetweetDetails(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(res, elem, weibo);
}
public RetweetDetails(JSONObject json) throws HttpException {
super();
init(json);
}
private void init(JSONObject json) throws HttpException{
try {
retweetId = json.getInt("retweetId");
retweetedAt = parseDate(json.getString("retweetedAt"), "EEE MMM dd HH:mm:ss z yyyy");
retweetingUser=new User(json.getJSONObject("retweetingUser"));
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
/*package*/public RetweetDetails(Response res, Element elem, Weibo weibo) throws
HttpException {
super(res);
init(res, elem, weibo);
}
private void init(Response res, Element elem, Weibo weibo) throws
HttpException {
ensureRootNodeNameIs("retweet_details", elem);
retweetId = getChildLong("retweet_id", elem);
retweetedAt = getChildDate("retweeted_at", elem);
retweetingUser = new User(res, (Element) elem.getElementsByTagName("retweeting_user").item(0)
, weibo);
}
public long getRetweetId() {
return retweetId;
}
public Date getRetweetedAt() {
return retweetedAt;
}
public User getRetweetingUser() {
return retweetingUser;
}
/*modify by sycheng add json*/
/*package*/
static List<RetweetDetails> createRetweetDetails(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<RetweetDetails> retweets = new ArrayList<RetweetDetails>(size);
for (int i = 0; i < size; i++) {
retweets.add(new RetweetDetails(list.getJSONObject(i)));
}
return retweets;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
/*package*/
static List<RetweetDetails> createRetweetDetails(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<RetweetDetails>(0);
} else {
try {
ensureRootNodeNameIs("retweets", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"retweet_details");
int size = list.getLength();
List<RetweetDetails> statuses = new ArrayList<RetweetDetails>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
statuses.add(new RetweetDetails(res, status, weibo));
}
return statuses;
} catch (HttpException te) {
ensureRootNodeNameIs("nil-classes", doc);
return new ArrayList<RetweetDetails>(0);
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RetweetDetails)) return false;
RetweetDetails that = (RetweetDetails) o;
return retweetId == that.retweetId;
}
@Override
public int hashCode() {
int result = (int) (retweetId ^ (retweetId >>> 32));
result = 31 * result + retweetedAt.hashCode();
result = 31 * result + retweetingUser.hashCode();
return result;
}
@Override
public String toString() {
return "RetweetDetails{" +
"retweetId=" + retweetId +
", retweetedAt=" + retweetedAt +
", retweetingUser=" + retweetingUser +
'}';
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/RetweetDetails.java | Java | asf20 | 6,255 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing sent/received direct message.
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class DirectMessage extends WeiboResponse implements java.io.Serializable {
private String id;
private String text;
private String sender_id;
private String recipient_id;
private Date created_at;
private String sender_screen_name;
private String recipient_screen_name;
private static final long serialVersionUID = -3253021825891789737L;
/*package*/DirectMessage(Response res, Weibo weibo) throws HttpException {
super(res);
init(res, res.asDocument().getDocumentElement(), weibo);
}
/*package*/DirectMessage(Response res, Element elem, Weibo weibo) throws HttpException {
super(res);
init(res, elem, weibo);
}
/*modify by sycheng add json call*/
/*package*/DirectMessage(JSONObject json) throws HttpException {
try {
id = json.getString("id");
text = json.getString("text");
sender_id = json.getString("sender_id");
recipient_id = json.getString("recipient_id");
created_at = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
sender_screen_name = json.getString("sender_screen_name");
recipient_screen_name = json.getString("recipient_screen_name");
if(!json.isNull("sender"))
sender = new User(json.getJSONObject("sender"));
if(!json.isNull("recipient"))
recipient = new User(json.getJSONObject("recipient"));
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
private void init(Response res, Element elem, Weibo weibo) throws HttpException{
ensureRootNodeNameIs("direct_message", elem);
sender = new User(res, (Element) elem.getElementsByTagName("sender").item(0),
weibo);
recipient = new User(res, (Element) elem.getElementsByTagName("recipient").item(0),
weibo);
id = getChildString("id", elem);
text = getChildText("text", elem);
sender_id = getChildString("sender_id", elem);
recipient_id = getChildString("recipient_id", elem);
created_at = getChildDate("created_at", elem);
sender_screen_name = getChildText("sender_screen_name", elem);
recipient_screen_name = getChildText("recipient_screen_name", elem);
}
public String getId() {
return id;
}
public String getText() {
return text;
}
public String getSenderId() {
return sender_id;
}
public String getRecipientId() {
return recipient_id;
}
/**
* @return created_at
* @since Weibo4J 1.1.0
*/
public Date getCreatedAt() {
return created_at;
}
public String getSenderScreenName() {
return sender_screen_name;
}
public String getRecipientScreenName() {
return recipient_screen_name;
}
private User sender;
public User getSender() {
return sender;
}
private User recipient;
public User getRecipient() {
return recipient;
}
/*package*/
static List<DirectMessage> constructDirectMessages(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<DirectMessage>(0);
} else {
try {
ensureRootNodeNameIs("direct-messages", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"direct_message");
int size = list.getLength();
List<DirectMessage> messages = new ArrayList<DirectMessage>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
messages.add(new DirectMessage(res, status, weibo));
}
return messages;
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new ArrayList<DirectMessage>(0);
} else {
throw te;
}
}
}
}
/*package*/
static List<DirectMessage> constructDirectMessages(Response res
) throws HttpException {
JSONArray list= res.asJSONArray();
try {
int size = list.length();
List<DirectMessage> messages = new ArrayList<DirectMessage>(size);
for (int i = 0; i < size; i++) {
messages.add(new DirectMessage(list.getJSONObject(i)));
}
return messages;
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
return obj instanceof DirectMessage && ((DirectMessage) obj).id.equals(this.id);
}
@Override
public String toString() {
return "DirectMessage{" +
"id=" + id +
", text='" + text + '\'' +
", sender_id=" + sender_id +
", recipient_id=" + recipient_id +
", created_at=" + created_at +
", sender_screen_name='" + sender_screen_name + '\'' +
", recipient_screen_name='" + recipient_screen_name + '\'' +
", sender=" + sender +
", recipient=" + recipient +
'}';
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/DirectMessage.java | Java | asf20 | 7,766 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
/**
* A data class representing Basic user information element
*/
public class Photo extends WeiboResponse implements java.io.Serializable {
private Weibo weibo;
private String thumbnail_pic;
private String bmiddle_pic;
private String original_pic;
private boolean verified;
private static final long serialVersionUID = -6345893237975349030L;
public Photo(JSONObject json) throws HttpException {
super();
init(json);
}
private void init(JSONObject json) throws HttpException {
try {
//System.out.println(json);
thumbnail_pic = json.getString("thumburl");
bmiddle_pic = json.getString("imageurl");
original_pic = json.getString("largeurl");
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
public String getThumbnail_pic() {
return thumbnail_pic;
}
public void setThumbnail_pic(String thumbnail_pic) {
this.thumbnail_pic = thumbnail_pic;
}
public String getBmiddle_pic() {
return bmiddle_pic;
}
public void setBmiddle_pic(String bmiddle_pic) {
this.bmiddle_pic = bmiddle_pic;
}
public String getOriginal_pic() {
return original_pic;
}
public void setOriginal_pic(String original_pic) {
this.original_pic = original_pic;
}
@Override
public String toString() {
return "Photo [thumbnail_pic=" + thumbnail_pic + ", bmiddle_pic="
+ bmiddle_pic + ", original_pic=" + original_pic + "]";
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/Photo.java | Java | asf20 | 3,160 |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Element;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Weibo rate limit status
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class RateLimitStatus extends WeiboResponse {
private int remainingHits;
private int hourlyLimit;
private int resetTimeInSeconds;
private Date resetTime;
private static final long serialVersionUID = 933996804168952707L;
/* package */ RateLimitStatus(Response res) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
remainingHits = getChildInt("remaining-hits", elem);
hourlyLimit = getChildInt("hourly-limit", elem);
resetTimeInSeconds = getChildInt("reset-time-in-seconds", elem);
resetTime = getChildDate("reset-time", elem, "EEE MMM d HH:mm:ss z yyyy");
}
/*modify by sycheng add json call*/
/* package */ RateLimitStatus(Response res,Weibo w) throws HttpException {
super(res);
JSONObject json= res.asJSONObject();
try {
remainingHits = json.getInt("remaining_hits");
hourlyLimit = json.getInt("hourly_limit");
resetTimeInSeconds = json.getInt("reset_time_in_seconds");
resetTime = parseDate(json.getString("reset_time"), "EEE MMM dd HH:mm:ss z yyyy");
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
public int getRemainingHits() {
return remainingHits;
}
public int getHourlyLimit() {
return hourlyLimit;
}
public int getResetTimeInSeconds() {
return resetTimeInSeconds;
}
/**
*
* @deprecated use getResetTime() instead
*/
@Deprecated
public Date getDateTime() {
return resetTime;
}
/**
* @since Weibo4J 2.0.9
*/
public Date getResetTime() {
return resetTime;
}
@Override
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append("RateLimitStatus{remainingHits:");
sb.append(remainingHits);
sb.append(";hourlyLimit:");
sb.append(hourlyLimit);
sb.append(";resetTimeInSeconds:");
sb.append(resetTimeInSeconds);
sb.append(";resetTime:");
sb.append(resetTime);
sb.append("}");
return sb.toString();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/fanfou/RateLimitStatus.java | Java | asf20 | 4,015 |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.os.Bundle;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
/**
* 随便看看
*
* @author jmx
*
*/
public class BrowseActivity extends TwitterCursorBaseActivity {
private static final String TAG = "BrowseActivity";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
mNavbar.setHeaderTitle(getActivityTitle());
getTweetList().removeFooterView(mListFooter); // 随便看看没有获取更多功能
return true;
} else {
return false;
}
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_browse);
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_BROWSE,
isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
return getApi().getPublicTimeline();
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public String fetchMinId() {
// 随便看看没有获取更多的功能
return null;
}
@Override
public List<Status> getMoreMessageFromId(String minId) throws HttpException {
// 随便看看没有获取更多的功能
return null;
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_BROWSE;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/BrowseActivity.java | Java | asf20 | 2,319 |
/*
* Copyright (C) 2009 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.
*/
package com.ch_linghu.fanfoudroid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.ImageManager;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
import com.ch_linghu.fanfoudroid.util.FileHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class WriteActivity extends BaseActivity {
// FIXME: for debug, delete me
private long startTime = -1;
private long endTime = -1;
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String REPLY_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPLY";
public static final String REPOST_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPOST";
public static final String EXTRA_REPLY_TO_NAME = "reply_to_name";
public static final String EXTRA_REPLY_ID = "reply_id";
public static final String EXTRA_REPOST_ID = "repost_status_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final int REQUEST_IMAGE_CAPTURE = 2;
private static final int REQUEST_PHOTO_LIBRARY = 3;
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private ImageButton mLocationButton;
private ImageButton chooseImagesButton;
private ImageButton mCameraButton;
private ProgressDialog dialog;
private NavBar mNavbar;
// Picture
private boolean withPic=false ;
private File mFile;
private ImageView mPreview;
private ImageView imageDelete;
private static final int MAX_BITMAP_SIZE = 400;
private File mImageFile;
private Uri mImageUri;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onSendBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
endTime = System.currentTimeMillis();
Log.d("LDS", "Sended a status in " + (endTime - startTime));
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onSendSuccess();
} else if (result == TaskResult.IO_ERROR) {
onSendFailure();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "SendTask";
}
};
private String _reply_id;
private String _repost_id;
private String _reply_to_name;
// sub menu
protected void openImageCaptureMenu() {
try {
// TODO: API < 1.6, images size too small
mImageFile = new File(FileHelper.getBasePath(), "upload.jpg");
mImageUri = Uri.fromFile(mImageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
protected void openPhotoLibraryMenu() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_PHOTO_LIBRARY);
}
/**
* @deprecated 已废弃, 分解成两个按钮
*/
protected void createInsertPhotoDialog() {
final CharSequence[] items = {
getString(R.string.write_label_take_a_picture),
getString(R.string.write_label_choose_a_picture) };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.write_label_insert_picture));
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
openImageCaptureMenu();
break;
case 1:
openPhotoLibraryMenu();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaColumns.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void getPic(Intent intent, Uri uri) {
// layout for picture mode
changeStyleWithPic();
withPic = true;
mFile = null;
mImageUri = uri;
if (uri.getScheme().equals("content")) {
mFile = new File(getRealPathFromURI(mImageUri));
} else {
mFile = new File(mImageUri.getPath());
}
// TODO:想将图片放在EditText左边
mPreview.setImageBitmap(createThumbnailBitmap(mImageUri,
MAX_BITMAP_SIZE));
if (mFile == null) {
updateProgress("Could not locate picture file. Sorry!");
disableEntry();
}
}
private File bitmapToFile(Bitmap bitmap) {
try {
File file = new File(FileHelper.getBasePath(), "upload.jpg");
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG,
ImageManager.DEFAULT_COMPRESS_QUALITY, out)) {
out.flush();
out.close();
}
return file;
} catch (FileNotFoundException e) {
Log.e(TAG, "Sorry, the file can not be created. " + e.getMessage());
return null;
} catch (IOException e) {
Log.e(TAG,
"IOException occurred when save upload file. "
+ e.getMessage());
return null;
}
}
private void changeStyleWithPic() {
// 修改布局 ,以前 图片居中,现在在左边
// mPreview.setLayoutParams(
// new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
// LayoutParams.FILL_PARENT)
// );
mPreview.setVisibility(View.VISIBLE);
imageDelete.setVisibility(View.VISIBLE);
mTweetEditText.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 2f));
}
/**
* 制作微缩图
*
* @param uri
* @param size
* @return
*/
private Bitmap createThumbnailBitmap(Uri uri, int size) {
InputStream input = null;
try {
input = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, options);
input.close();
// Compute the scale.
int scale = 1;
while ((options.outWidth / scale > size)
|| (options.outHeight / scale > size)) {
scale *= 2;
}
options.inJustDecodeBounds = false;
options.inSampleSize = scale;
input = getContentResolver().openInputStream(uri);
return BitmapFactory.decodeStream(input, null, options);
} catch (IOException e) {
Log.w(TAG, e);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
// init View
setContentView(R.layout.write);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
Bundle extras = intent.getExtras();
String text = null;
Uri uri = null;
if (extras != null) {
String subject = extras.getString(Intent.EXTRA_SUBJECT);
text = extras.getString(Intent.EXTRA_TEXT);
uri = (Uri) (extras.get(Intent.EXTRA_STREAM));
if (!TextUtils.isEmpty(subject)) {
text = subject + " " + text;
}
if ((type != null && type.startsWith("text")) && uri != null) {
text = text + " " + uri.toString();
uri = null;
}
}
_reply_id = null;
_repost_id = null;
_reply_to_name = null;
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
// TODO: @某人-- 类似饭否自动补全
ImageButton mAddUserButton = (ImageButton) findViewById(R.id.add_user);
mAddUserButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int start = mTweetEditText.getSelectionStart();
int end = mTweetEditText.getSelectionEnd();
mTweetEditText.getText().replace(Math.min(start, end),
Math.max(start, end), "@");
}
});
// 插入图片
chooseImagesButton = (ImageButton) findViewById(R.id.choose_images_button);
chooseImagesButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "chooseImagesButton onClick");
openPhotoLibraryMenu();
}
});
// 打开相机
mCameraButton = (ImageButton) findViewById(R.id.camera_button);
mCameraButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "mCameraButton onClick");
openImageCaptureMenu();
}
});
// With picture
imageDelete = (ImageView) findViewById(R.id.image_delete);
imageDelete.setOnClickListener(deleteListener);
mPreview = (ImageView) findViewById(R.id.preview);
if (Intent.ACTION_SEND.equals(intent.getAction()) && uri != null) {
getPic(intent, uri);
}
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
if (TwitterApplication.mPref.getBoolean(Preferences.USE_ENTER_SEND, false)){
mTweetEdit.setOnKeyListener(tweetEnterHandler);
}
mTweetEdit.addTextChangedListener(new MyTextWatcher(
WriteActivity.this));
if (NEW_TWEET_ACTION.equals(action) || Intent.ACTION_SEND.equals(action)){
if (!TextUtils.isEmpty(text)){
//始终将光标置于最末尾,以方便回复消息时保持@用户在最前面
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(text);
Editable etext = inputField.getText();
int position = etext.length();
Selection.setSelection(etext, position);
}
}else if (REPLY_TWEET_ACTION.equals(action)) {
_reply_id = intent.getStringExtra(EXTRA_REPLY_ID);
_reply_to_name = intent.getStringExtra(EXTRA_REPLY_TO_NAME);
if (!TextUtils.isEmpty(text)){
String reply_to_name = "@"+_reply_to_name + " ";
String other_replies = "";
for (String mention : TextHelper.getMentions(text)){
//获取名字时不包括自己和回复对象
if (!mention.equals(TwitterApplication.getMyselfName()) &&
!mention.equals(_reply_to_name)){
other_replies += "@"+mention+" ";
}
}
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(reply_to_name + other_replies);
//将除了reply_to_name的其他名字默认选中
Editable etext = inputField.getText();
int start = reply_to_name.length();
int stop = etext.length();
Selection.setSelection(etext, start, stop);
}
}else if (REPOST_TWEET_ACTION.equals(action)) {
if (!TextUtils.isEmpty(text)){
// 如果是转发消息,则根据用户习惯,将光标放置在转发消息的头部或尾部
SharedPreferences prefereces = getPreferences();
boolean isAppendToTheBeginning = prefereces.getBoolean(
Preferences.RT_INSERT_APPEND, true);
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(text);
Editable etext = inputField.getText();
int position = (isAppendToTheBeginning) ? 0 : etext.length();
Selection.setSelection(etext, position);
}
}
mLocationButton = (ImageButton) findViewById(R.id.location_button);
mLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(WriteActivity.this, "LBS地理定位功能开发中, 敬请期待",
Toast.LENGTH_SHORT).show();
}
});
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
});
return true;
} else {
return false;
}
}
private View.OnClickListener deleteListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
intent.setAction(null);
withPic = false;
mPreview.setVisibility(View.INVISIBLE);
imageDelete.setVisibility(View.INVISIBLE);
}
};
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
if (dialog != null) {
dialog.dismiss();
}
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
return intent;
}
public static Intent createNewReplyIntent(String tweetText, String screenName, String replyId) {
Intent intent = new Intent(WriteActivity.REPLY_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, TextHelper.getSimpleTweetText(tweetText));
intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME, screenName);
intent.putExtra(WriteActivity.EXTRA_REPLY_ID, replyId);
return intent;
}
public static Intent createNewRepostIntent(Context content,
String tweetText, String screenName, String repostId) {
SharedPreferences mPreferences = PreferenceManager
.getDefaultSharedPreferences(content);
String prefix = mPreferences.getString(Preferences.RT_PREFIX_KEY,
content.getString(R.string.pref_rt_prefix_default));
String retweet = " " + prefix + " @" + screenName + " "
+ TextHelper.getSimpleTweetText(tweetText);
Intent intent = new Intent(WriteActivity.REPOST_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, retweet);
intent.putExtra(WriteActivity.EXTRA_REPOST_ID, repostId);
return intent;
}
public static Intent createImageIntent(Activity activity, Uri uri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
WriteActivity writeActivity = (WriteActivity) activity;
intent.putExtra(Intent.EXTRA_TEXT,
writeActivity.mTweetEdit.getText());
intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME,
writeActivity._reply_to_name);
intent.putExtra(WriteActivity.EXTRA_REPLY_ID,
writeActivity._reply_id);
intent.putExtra(WriteActivity.EXTRA_REPOST_ID,
writeActivity._repost_id);
} catch (ClassCastException e) {
// do nothing
}
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteActivity _activity;
public MyTextWatcher(WriteActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
_activity._reply_id = null;
_activity._reply_to_name = null;
_activity._repost_id = null;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private View.OnKeyListener tweetEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
WriteActivity t = (WriteActivity) (v.getContext());
doSend();
}
return true;
}
return false;
}
};
private void doSend() {
Log.d(TAG, "dosend "+withPic);
startTime = System.currentTimeMillis();
Log.d(TAG, String.format("doSend, reply_id=%s", _reply_id));
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) || withPic) {
int mode = SendTask.TYPE_NORMAL;
if (withPic) {
mode = SendTask.TYPE_PHOTO;
} else if (null != _reply_id) {
mode = SendTask.TYPE_REPLY;
} else if (null != _repost_id) {
mode = SendTask.TYPE_REPOST;
}
mSendTask = new SendTask();
mSendTask.setListener(mSendTaskListener);
TaskParams params = new TaskParams();
params.put("mode", mode);
mSendTask.execute(params);
} else {
updateProgress(getString(R.string.page_text_is_null));
}
}
}
private class SendTask extends GenericTask {
public static final int TYPE_NORMAL = 0;
public static final int TYPE_REPLY = 1;
public static final int TYPE_REPOST = 2;
public static final int TYPE_PHOTO = 3;
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String status = mTweetEdit.getText().toString();
int mode = param.getInt("mode");
Log.d(TAG, "Send Status. Mode : " + mode);
// Send status in different way
switch (mode) {
case TYPE_REPLY:
// 增加容错性,即使reply_id为空依然允许发送
if (null == WriteActivity.this._reply_id) {
Log.e(TAG,
"Cann't send status in REPLY mode, reply_id is null");
}
getApi().updateStatus(status, WriteActivity.this._reply_id);
break;
case TYPE_REPOST:
// 增加容错性,即使repost_id为空依然允许发送
if (null == WriteActivity.this._repost_id) {
Log.e(TAG,
"Cann't send status in REPOST mode, repost_id is null");
}
getApi().repost(status, WriteActivity.this._repost_id);
break;
case TYPE_PHOTO:
if (null != mFile) {
// Compress image
try {
mFile = getImageManager().compressImage(mFile, 100);
//ImageManager.DEFAULT_COMPRESS_QUALITY);
} catch (IOException ioe) {
Log.e(TAG, "Cann't compress images.");
}
getApi().updateStatus(status, mFile);
} else {
Log.e(TAG,
"Cann't send status in PICTURE mode, photo is null");
}
break;
case TYPE_NORMAL:
default:
getApi().updateStatus(status); // just send a status
break;
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
if (e.getStatusCode() == HttpClient.NOT_AUTHORIZED) {
return TaskResult.AUTH_ERROR;
}
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
private ImageManager getImageManager() {
return TwitterApplication.mImageLoader.getImageManager();
}
}
private void onSendBegin() {
disableEntry();
dialog = ProgressDialog.show(WriteActivity.this, "",
getString(R.string.page_status_updating), true);
if (dialog != null) {
dialog.setCancelable(false);
}
updateProgress(getString(R.string.page_status_updating));
}
private void onSendSuccess() {
if (dialog != null) {
dialog.setMessage(getString(R.string.page_status_update_success));
dialog.dismiss();
}
_reply_id = null;
_repost_id = null;
updateProgress(getString(R.string.page_status_update_success));
enableEntry();
// FIXME: 不理解这段代码的含义,暂时注释掉
// try {
// Thread.currentThread();
// Thread.sleep(500);
// updateProgress("");
// } catch (InterruptedException e) {
// Log.d(TAG, e.getMessage());
// }
updateProgress("");
// 发送成功就自动关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(),
0);
}
private void onSendFailure() {
dialog.setMessage(getString(R.string.page_status_unable_to_update));
dialog.dismiss();
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mLocationButton.setEnabled(true);
chooseImagesButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mLocationButton.setEnabled(false);
chooseImagesButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Intent intent = WriteActivity.createImageIntent(this, mImageUri);
//照相完后不重新起一个WriteActivity
getPic(intent, mImageUri);
/*intent.setClass(this, WriteActivity.class);
startActivity(intent);
// 打开发送图片界面后将自身关闭
finish();*/
} else if (requestCode == REQUEST_PHOTO_LIBRARY
&& resultCode == RESULT_OK) {
mImageUri = data.getData();
Intent intent = WriteActivity.createImageIntent(this, mImageUri);
//选图片后不重新起一个WriteActivity
getPic(intent, mImageUri);
/*intent.setClass(this, WriteActivity.class);
startActivity(intent);
// 打开发送图片界面后将自身关闭
finish();*/
}
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/WriteActivity.java | Java | asf20 | 29,383 |
package com.ch_linghu.fanfoudroid;
import com.ch_linghu.fanfoudroid.app.Preferences;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
//set real version
ComponentName comp = new ComponentName(this, getClass());
PackageInfo pinfo = null;
try {
pinfo = getPackageManager().getPackageInfo(comp.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView version = (TextView)findViewById(R.id.version);
version.setText(String.format("v %s", pinfo.versionName));
//bind button click event
Button okBtn = (Button)findViewById(R.id.ok_btn);
okBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/AboutActivity.java | Java | asf20 | 1,534 |
package com.ch_linghu.fanfoudroid;
import java.util.HashSet;
//import org.acra.ReportingInteractionMode;
//import org.acra.annotation.ReportsCrashes;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
//@ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ",
// mode = ReportingInteractionMode.NOTIFICATION,
// resNotifTickerText = R.string.crash_notif_ticker_text,
// resNotifTitle = R.string.crash_notif_title,
// resNotifText = R.string.crash_notif_text,
// resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign
// resDialogText = R.string.crash_dialog_text,
// resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign
// resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name
// resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label
// resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report.
//)
public class TwitterApplication extends Application {
public static final String TAG = "TwitterApplication";
// public static ImageManager mImageManager;
public static LazyImageLoader mImageLoader;
public static TwitterDatabase mDb;
public static Weibo mApi; // new API
public static Context mContext;
public static SharedPreferences mPref;
public static int networkType = 0;
public final static boolean DEBUG = Configuration.getDebug();
// FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道
// 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器
// 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户
// 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。
// 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID
// 到mPref.
private static void fetchMyselfInfo() {
User myself;
try {
myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi.getUserId());
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_ID, myself.getId()).commit();
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_SCREEN_NAME, myself.getScreenName()).commit();
} catch (HttpException e) {
e.printStackTrace();
}
}
public static String getMyselfId() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_ID, "~");
}
public static String getMyselfName() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, "");
}
@Override
public void onCreate() {
// FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。
// 因此将这些代码设成关闭状态,仅在做性能调试时才打开。
// //NOTE: StrictMode模式需要2.3+ API支持。
// if (DEBUG){
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// }
super.onCreate();
mContext = this.getApplicationContext();
// mImageManager = new ImageManager(this);
mImageLoader = new LazyImageLoader();
mApi = new Weibo();
mDb = TwitterDatabase.getInstance(this);
mPref = PreferenceManager.getDefaultSharedPreferences(this);
String username = mPref.getString(Preferences.USERNAME_KEY, "");
String password = mPref.getString(Preferences.PASSWORD_KEY, "");
password = LoginActivity.decryptPassword(password);
if (Weibo.isValidCredentials(username, password)) {
mApi.setCredentials(username, password); // Setup API and HttpClient
}
// 为cmwap用户设置代理上网
String type = getNetworkType();
if (null != type && type.equalsIgnoreCase("cmwap")) {
Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT);
mApi.getHttpClient().setProxy("10.0.0.172", 80, "http");
}
}
public String getNetworkType() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
//NetworkInfo mobNetInfo = connectivityManager
// .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNetInfo != null){
return activeNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap, cmnet,
// internet ...
}else{
return null;
}
}
@Override
public void onTerminate() {
//FIXME: 根据android文档,onTerminate不会在真实机器上被执行到
//因此这些清理动作需要再找合适的地方放置,以确保执行。
cleanupImages();
mDb.close();
Toast.makeText(this, "exit app", Toast.LENGTH_LONG);
super.onTerminate();
}
private void cleanupImages() {
HashSet<String> keepers = new HashSet<String>();
Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
cursor = mDb.fetchAllDms(-1);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
mImageLoader.getImageManager().cleanup(keepers);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/TwitterApplication.java | Java | asf20 | 6,960 |
package com.ch_linghu.fanfoudroid.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Html;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;
import android.widget.TextView.BufferType;
public class TextHelper {
private static final String TAG = "TextHelper";
public static String stringifyStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>();
private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s");
private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() {
@Override
public final boolean acceptMatch(final CharSequence s, final int start,
final int end) {
String name = s.subSequence(start + 1, end).toString().trim();
boolean result = _userLinkMapping.containsKey(name);
return result;
}
};
private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
// TODO Auto-generated method stub
String name = url.subSequence(1, url.length()).toString().trim();
return _userLinkMapping.get(name);
}
};
private static final String TWITTA_USER_URL = "twitta://users/";
public static void linkifyUsers(TextView view) {
Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL,
NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER);
}
private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#");
private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public final String transformUrl(Matcher match, String url) {
String result = url.substring(1, url.length() - 1);
return "%23" + result + "%23";
}
};
private static final String TWITTA_SEARCH_URL = "twitta://search/";
public static void linkifyTags(TextView view) {
Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null,
TAG_MATCHER_TRANSFORM_FILTER);
}
private static Pattern USER_LINK = Pattern
.compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>");
private static String preprocessText(String text) {
// 处理HTML格式返回的用户链接
Matcher m = USER_LINK.matcher(text);
while (m.find()) {
_userLinkMapping.put(m.group(2), m.group(1));
Log.d(TAG,
String.format("Found mapping! %s=%s", m.group(2),
m.group(1)));
}
// 将User Link的连接去掉
StringBuffer sb = new StringBuffer();
m = USER_LINK.matcher(text);
while (m.find()) {
m.appendReplacement(sb, "@$2");
}
m.appendTail(sb);
return sb.toString();
}
public static String getSimpleTweetText(String text) {
return Html.fromHtml(text).toString();
}
public static void setSimpleTweetText(TextView textView, String text) {
String processedText = getSimpleTweetText(text);
textView.setText(processedText);
}
public static void setTweetText(TextView textView, String text) {
String processedText = preprocessText(text);
textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE);
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
linkifyUsers(textView);
linkifyTags(textView);
_userLinkMapping.clear();
}
/**
* 从消息中获取全部提到的人,将它们按先后顺序放入一个列表
* @param msg 消息文本
* @return 消息中@的人的列表,按顺序存放
*/
public static List<String> getMentions(String msg){
ArrayList<String> mentionList = new ArrayList<String>();
final Pattern p = Pattern.compile("@(.*?)\\s");
final int MAX_NAME_LENGTH = 12; //简化判断,无论中英文最长12个字
Matcher m = p.matcher(msg);
while(m.find()){
String mention = m.group(1);
//过长的名字就忽略(不是合法名字) +1是为了补上“@”所占的长度
if (mention.length() <= MAX_NAME_LENGTH+1){
//避免重复名字
if (!mentionList.contains(mention)){
mentionList.add(m.group(1));
}
}
}
return mentionList;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/util/TextHelper.java | Java | asf20 | 5,209 |
package com.ch_linghu.fanfoudroid.util;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamUtils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
} | 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/util/StreamUtils.java | Java | asf20 | 572 |
package com.ch_linghu.fanfoudroid.util;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.HashMap;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
/**
* Debug Timer
*
* Usage:
* --------------------------------
* DebugTimer.start();
* DebugTimer.mark("my_mark1"); // optional
* DebugTimer.stop();
*
* System.out.println(DebugTimer.__toString()); // get report
* --------------------------------
*
* @author LDS
*/
public class DebugTimer {
public static final int START = 0;
public static final int END = 1;
private static HashMap<String, Long> mTime = new HashMap<String, Long>();
private static long mStartTime = 0;
private static long mLastTime = 0;
/**
* Start a timer
*/
public static void start() {
reset();
mStartTime = touch();
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long mark(String tag) {
long time = System.currentTimeMillis() - mStartTime;
mTime.put(tag, time);
return time;
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long between(String tag, int startOrEnd) {
if(TwitterApplication.DEBUG){
Log.v("DEBUG", tag + " " + startOrEnd);
}
switch (startOrEnd) {
case START:
return mark(tag);
case END:
long time = System.currentTimeMillis() - mStartTime - get(tag, mStartTime);
mTime.put(tag, time);
//touch();
return time;
default:
return -1;
}
}
public static long betweenStart(String tag) {
return between(tag, START);
}
public static long betweenEnd(String tag) {
return between(tag, END);
}
/**
* Stop timer
*
* @return result
*/
public static String stop() {
mTime.put("_TOTLE", touch() - mStartTime);
return __toString();
}
public static String stop(String tag) {
mark(tag);
return stop();
}
/**
* Get a mark time
*
* @param tag mark tag
* @return time(milliseconds) or NULL
*/
public static long get(String tag) {
return get(tag, 0);
}
public static long get(String tag, long defaultValue) {
if (mTime.containsKey(tag)) {
return mTime.get(tag);
}
return defaultValue;
}
/**
* Reset timer
*/
public static void reset() {
mTime = new HashMap<String, Long>();
mStartTime = 0;
mLastTime = 0;
}
/**
* static toString()
*
* @return
*/
public static String __toString() {
return "Debuger [time =" + mTime.toString() + "]";
}
private static long touch() {
return mLastTime = System.currentTimeMillis();
}
public static DebugProfile[] getProfile() {
DebugProfile[] profile = new DebugProfile[mTime.size()];
long totel = mTime.get("_TOTLE");
int i = 0;
for (String key : mTime.keySet()) {
long time = mTime.get(key);
profile[i] = new DebugProfile(key, time, time/(totel*1.0) );
i++;
}
try {
Arrays.sort(profile);
} catch (NullPointerException e) {
// in case item is null, do nothing
}
return profile;
}
public static String getProfileAsString() {
StringBuilder sb = new StringBuilder();
for (DebugProfile p : getProfile()) {
sb.append("TAG: ");
sb.append(p.tag);
sb.append("\t INC: ");
sb.append(p.inc);
sb.append("\t INCP: ");
sb.append(p.incPercent);
sb.append("\n");
}
return sb.toString();
}
@Override
public String toString() {
return __toString();
}
}
class DebugProfile implements Comparable<DebugProfile> {
private static NumberFormat percent = NumberFormat.getPercentInstance();
public String tag;
public long inc;
public String incPercent;
public DebugProfile(String tag, long inc, double incPercent) {
this.tag = tag;
this.inc = inc;
percent = new DecimalFormat("0.00#%");
this.incPercent = percent.format(incPercent);
}
@Override
public int compareTo(DebugProfile o) {
// TODO Auto-generated method stub
return (int) (o.inc - this.inc);
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/util/DebugTimer.java | Java | asf20 | 4,762 |
package com.ch_linghu.fanfoudroid.util;
import java.io.File;
import java.io.IOException;
import android.os.Environment;
/**
* 对SD卡文件的管理
* @author ch.linghu
*
*/
public class FileHelper {
private static final String TAG = "FileHelper";
private static final String BASE_PATH="fanfoudroid";
public static File getBasePath() throws IOException{
File basePath = new File(Environment.getExternalStorageDirectory(),
BASE_PATH);
if (!basePath.exists()){
if (!basePath.mkdirs()){
throw new IOException(String.format("%s cannot be created!", basePath.toString()));
}
}
if (!basePath.isDirectory()){
throw new IOException(String.format("%s is not a directory!", basePath.toString()));
}
return basePath;
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/util/FileHelper.java | Java | asf20 | 813 |
package com.ch_linghu.fanfoudroid.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class DateTimeHelper {
private static final String TAG = "DateTimeHelper";
// Wed Dec 15 02:53:36 +0000 2010
public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat(
"E MMM d HH:mm:ss Z yyyy", Locale.US);
public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat(
"E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ?
public static final Date parseDateTime(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TWITTER_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
// Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite
public static final Date parseDateTimeFromSqlite(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
public static final Date parseSearchApiDateTime(String dateString) {
try {
return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter search date string: "
+ dateString);
return null;
}
}
public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static String getRelativeDate(Date date) {
Date now = new Date();
String prefix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_prefix);
String sec = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_sec);
String min = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_min);
String hour = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_hour);
String day = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_day);
String suffix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_suffix);
// Seconds.
long diff = (now.getTime() - date.getTime()) / 1000;
if (diff < 0) {
diff = 0;
}
if (diff < 60) {
return diff + sec + suffix;
}
// Minutes.
diff /= 60;
if (diff < 60) {
return prefix + diff + min + suffix;
}
// Hours.
diff /= 60;
if (diff < 24) {
return prefix + diff + hour + suffix;
}
return AGO_FULL_DATE_FORMATTER.format(date);
}
public static long getNowTime() {
return Calendar.getInstance().getTime().getTime();
}
}
| 061304011116lyj-aa | src/com/ch_linghu/fanfoudroid/util/DateTimeHelper.java | Java | asf20 | 3,539 |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 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.
*/
package com.commonsware.cwac.sacklist;
import java.util.ArrayList;
import java.util.List;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* Adapter that simply returns row views from a list.
*
* If you supply a size, you must implement newView(), to
* create a required view. The adapter will then cache these
* views.
*
* If you supply a list of views in the constructor, that
* list will be used directly. If any elements in the list
* are null, then newView() will be called just for those
* slots.
*
* Subclasses may also wish to override areAllItemsEnabled()
* (default: false) and isEnabled() (default: false), if some
* of their rows should be selectable.
*
* It is assumed each view is unique, and therefore will not
* get recycled.
*
* Note that this adapter is not designed for long lists. It
* is more for screens that should behave like a list. This
* is particularly useful if you combine this with other
* adapters (e.g., SectionedAdapter) that might have an
* arbitrary number of rows, so it all appears seamless.
*/
public class SackOfViewsAdapter extends BaseAdapter {
private List<View> views=null;
/**
* Constructor creating an empty list of views, but with
* a specified count. Subclasses must override newView().
*/
public SackOfViewsAdapter(int count) {
super();
views=new ArrayList<View>(count);
for (int i=0;i<count;i++) {
views.add(null);
}
}
/**
* Constructor wrapping a supplied list of views.
* Subclasses must override newView() if any of the elements
* in the list are null.
*/
public SackOfViewsAdapter(List<View> views) {
super();
this.views=views;
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
return(views.get(position));
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
return(views.size());
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
return(getCount());
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
return(position);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View result=views.get(position);
if (result==null) {
result=newView(position, parent);
views.set(position, result);
}
return(result);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
return(position);
}
/**
* Create a new View to go into the list at the specified
* position.
* @param position Position of the item whose data we want
* @param parent ViewGroup containing the returned View
*/
protected View newView(int position, ViewGroup parent) {
throw new RuntimeException("You must override newView()!");
}
} | 061304011116lyj-aa | src/com/commonsware/cwac/sacklist/SackOfViewsAdapter.java | Java | asf20 | 4,593 |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 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.
*/
package com.commonsware.cwac.merge;
import java.util.ArrayList;
import java.util.List;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SectionIndexer;
import com.commonsware.cwac.sacklist.SackOfViewsAdapter;
/**
* Adapter that merges multiple child adapters and views
* into a single contiguous whole.
*
* Adapters used as pieces within MergeAdapter must
* have view type IDs monotonically increasing from 0. Ideally,
* adapters also have distinct ranges for their row ids, as
* returned by getItemId().
*
*/
public class MergeAdapter extends BaseAdapter implements SectionIndexer {
private ArrayList<ListAdapter> pieces=new ArrayList<ListAdapter>();
/**
* Stock constructor, simply chaining to the superclass.
*/
public MergeAdapter() {
super();
}
/**
* Adds a new adapter to the roster of things to appear
* in the aggregate list.
* @param adapter Source for row views for this section
*/
public void addAdapter(ListAdapter adapter) {
pieces.add(adapter);
adapter.registerDataSetObserver(new CascadeDataSetObserver());
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
*/
public void addView(View view) {
addView(view, false);
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
* @param enabled false if views are disabled, true if enabled
*/
public void addView(View view, boolean enabled) {
ArrayList<View> list=new ArrayList<View>(1);
list.add(view);
addViews(list, enabled);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
*/
public void addViews(List<View> views) {
addViews(views, false);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
* @param enabled false if views are disabled, true if enabled
*/
public void addViews(List<View> views, boolean enabled) {
if (enabled) {
addAdapter(new EnabledSackAdapter(views));
}
else {
addAdapter(new SackOfViewsAdapter(views));
}
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItem(position));
}
position-=size;
}
return(null);
}
/**
* Get the adapter associated with the specified
* position in the data set.
* @param position Position of the item whose adapter we want
*/
public ListAdapter getAdapter(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece);
}
position-=size;
}
return(null);
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getCount();
}
return(total);
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getViewTypeCount();
}
return(Math.max(total, 1)); // needed for setListAdapter() before content add'
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
int typeOffset=0;
int result=-1;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
result=typeOffset+piece.getItemViewType(position);
break;
}
position-=size;
typeOffset+=piece.getViewTypeCount();
}
return(result);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.isEnabled(position));
}
position-=size;
}
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getView(position, convertView, parent));
}
position-=size;
}
return(null);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItemId(position));
}
position-=size;
}
return(-1);
}
@Override
public int getPositionForSection(int section) {
int position=0;
for (ListAdapter piece : pieces) {
if (piece instanceof SectionIndexer) {
Object[] sections=((SectionIndexer)piece).getSections();
int numSections=0;
if (sections!=null) {
numSections=sections.length;
}
if (section<numSections) {
return(position+((SectionIndexer)piece).getPositionForSection(section));
}
else if (sections!=null) {
section-=numSections;
}
}
position+=piece.getCount();
}
return(0);
}
@Override
public int getSectionForPosition(int position) {
int section=0;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
if (piece instanceof SectionIndexer) {
return(section+((SectionIndexer)piece).getSectionForPosition(position));
}
return(0);
}
else {
if (piece instanceof SectionIndexer) {
Object[] sections=((SectionIndexer)piece).getSections();
if (sections!=null) {
section+=sections.length;
}
}
}
position-=size;
}
return(0);
}
@Override
public Object[] getSections() {
ArrayList<Object> sections=new ArrayList<Object>();
for (ListAdapter piece : pieces) {
if (piece instanceof SectionIndexer) {
Object[] curSections=((SectionIndexer)piece).getSections();
if (curSections!=null) {
for (Object section : curSections) {
sections.add(section);
}
}
}
}
if (sections.size()==0) {
return(null);
}
return(sections.toArray(new Object[0]));
}
private static class EnabledSackAdapter extends SackOfViewsAdapter {
public EnabledSackAdapter(List<View> views) {
super(views);
}
@Override
public boolean areAllItemsEnabled() {
return(true);
}
@Override
public boolean isEnabled(int position) {
return(true);
}
}
private class CascadeDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
}
} | 061304011116lyj-aa | src/com/commonsware/cwac/merge/MergeAdapter.java | Java | asf20 | 8,420 |
package com.hlidskialf.android.hardware;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener {
private static final int FORCE_THRESHOLD = 350;
private static final int TIME_THRESHOLD = 100;
private static final int SHAKE_TIMEOUT = 500;
private static final int SHAKE_DURATION = 1000;
private static final int SHAKE_COUNT = 3;
private SensorManager mSensorMgr;
private Sensor mSensor;
private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f;
private long mLastTime;
private OnShakeListener mShakeListener;
private Context mContext;
private int mShakeCount = 0;
private long mLastShake;
private long mLastForce;
public interface OnShakeListener {
public void onShake();
}
public ShakeListener(Context context) {
mContext = context;
resume();
}
public void setOnShakeListener(OnShakeListener listener) {
mShakeListener = listener;
}
public void resume() {
mSensorMgr = (SensorManager) mContext
.getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorMgr
.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);
if (mSensorMgr == null) {
throw new UnsupportedOperationException("Sensors not supported");
}
boolean supported = mSensorMgr.registerListener(this,
mSensor,
SensorManager.SENSOR_DELAY_GAME);
if (!supported) {
mSensorMgr.unregisterListener(this, mSensor);
throw new UnsupportedOperationException(
"Accelerometer not supported");
}
}
public void pause() {
if (mSensorMgr != null) {
mSensorMgr.unregisterListener(this,
mSensor);
mSensorMgr = null;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (sensor.getType() != SensorManager.SENSOR_ACCELEROMETER)
return;
long now = System.currentTimeMillis();
if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}
if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(values[SensorManager.DATA_X]
+ values[SensorManager.DATA_Y]
+ values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ)
/ diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT)
&& (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
if (mShakeListener != null) {
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = values[SensorManager.DATA_X];
mLastY = values[SensorManager.DATA_Y];
mLastZ = values[SensorManager.DATA_Z];
}
}
}
| 061304011116lyj-aa | src/com/hlidskialf/android/hardware/ShakeListener.java | Java | asf20 | 2,826 |
/* Javadoc 样式表 */
/* 在此处定义颜色、字体和其他样式属性以覆盖默认值 */
/* 页面背景颜色 */
body { background-color: #FFFFFF; color:#000000 }
/* 标题 */
h1 { font-size: 145% }
/* 表格颜色 */
.TableHeadingColor { background: #CCCCFF; color:#000000 } /* 深紫色 */
.TableSubHeadingColor { background: #EEEEFF; color:#000000 } /* 淡紫色 */
.TableRowColor { background: #FFFFFF; color:#000000 } /* 白色 */
/* 左侧的框架列表中使用的字体 */
.FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif; color:#000000 }
.FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 }
.FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 }
/* 导航栏字体和颜色 */
.NavBarCell1 { background-color:#EEEEFF; color:#000000} /* 淡紫色 */
.NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* 深蓝色 */
.NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;color:#000000;}
.NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;color:#FFFFFF;}
.NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000}
.NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000}
| 061304011116lyj-aa | doc/stylesheet.css | CSS | asf20 | 1,370 |
#!/bin/bash
# 打开apache.http调试信息
adb shell setprop log.tag.org.apache.http VERBOSE
adb shell setprop log.tag.org.apache.http.wire VERBOSE
adb shell setprop log.tag.org.apache.http.headers VERBOSE
echo "Enable Debug"
| 061304011116lyj-aa | tools/openHttpDebug.sh | Shell | asf20 | 229 |
<?php
function load() {
header('Content-Type: text/text; charset=GBK');
$code = $_GET['code'];
if ($code == "") {
header('Location: https://oauth.taobao.com/authorize?response_type=code&redirect_uri=http://eagleonhill.oicp.net/editor/taobao.php&client_id=21134472');
} else {
chdir('../../donation-dir');
echo passthru('taobao.bat "' . $code . '"');
}
}
load();
?>
| 007slmg-np-activex-justep | web/taobao.php | PHP | mpl11 | 400 |
.itemline.newline:not(.editing) {
display:none;
}
.list {
width: 100%;
height: 520px;
}
div[property=title] {
width: 200px
}
div[property=type] {
width: 60px
}
div[property=value] {
width: 240px
}
div[property=enabled] {
width: 60px
}
div[property=userAgent] {
width: 70px
}
div[property=script] {
width: 200px
}
div[property=description] {
width: 300px
}
div[property=url] {
width: 300px
}
div[property=compute], div[property=compute] button{
width: 80px
}
div[property=checksum] {
width: 80px
}
[property=status] button {
width: 70px;
}
#scriptEditor {
display: block;
width: 100%;
height: 361px;
}
| 007slmg-np-activex-justep | web/editor.css | CSS | mpl11 | 694 |
.list {
width: 800px;
height: 400px;
font-family: Arial, sans-serif;
overflow-x: hidden;
border: 3px solid #0D5995;
background-color: #0D5995;
padding: 1px;
padding-top: 10px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
.listscroll {
overflow-x: scroll;
overflow-y: scroll;
background-color: white;
}
.listitems {
display: inline-block;
}
.listvalue, .header {
display: inline-block;
width: 80px;
margin: 0px 6px;
}
.headers {
background-color: transparent;
position: relative;
white-space: nowrap;
display: inline-block;
color:white;
padding: 5px 0px;
}
.header{
white-space: normal;
}
.itemline {
height: 32px;
}
.itemline:nth-child(odd) {
background-color: white;
}
.itemline:nth-child(even) {
background-color: whitesmoke;
}
.itemline.selected {
background-color: #aaa;
}
.itemline:hover {
background-color: #bbcee9
}
.itemline.error,
.itemline.error:hover {
background-color: salmon;
}
.itemline > div {
white-space: nowrap;
padding: 4px 0px 0 0;
}
.itemline.editing > div{
padding: 3px 0px 0 0;
}
.valdisp, .valinput {
background-color: transparent;
width: 100%;
display: block;
}
.listvalue {
overflow-x: hidden;
}
.itemline.editing .listvalue:not(.readonly) .valdisp {
display: none;
}
.valdisp {
font-size: 13px;
}
.itemline:not(.editing) .valinput,
.listvalue.readonly .valinput {
display: none;
}
.itemline :focus {
outline: none;
}
.valinput {
border:1px solid #aaa;
background-color: white;
padding: 3px;
margin: 0;
}
.itemline .valinput:focus {
outline-color: rgba(0, 128, 256, 0.5);
outline: 5px auto rgba(0, 128, 256, 0.5);
}
| 007slmg-np-activex-justep | web/list.css | CSS | mpl11 | 1,865 |
<?php
function load() {
$postData = '';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$postData .= "&$key=$value";
}
$postData = substr($postData, 1);
if (!isset($_POST['item_number']) || $_POST['item_number'] != 'npax') {
echo 'Not relevant item';
return;
}
chdir('../../donation-dir');
echo exec('paypal.bat "' . $postData . '"');
}
load();
?>
| 007slmg-np-activex-justep | web/paypal.php | PHP | mpl11 | 430 |
<html>
<head>
<script>
function stringHash(str) {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
ch = str.charCodeAt(i);
hash = ((hash << 5) - hash) + ch;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
function compute() {
result.innerText = stringHash(text.value);
}
</script>
</head>
<body>
<textarea id="text" style="width: 700px; height:500px; margin:auto"></textarea>
<div id="result"></div>
<button onclick="compute()">Compute</button>
</body>
</html>
| 007slmg-np-activex-justep | web/stringhash.html | HTML | mpl11 | 672 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
prop = {
header, // String
property, // String
events, //
type, // checkbox, select, input.type, button
extra // depend on type
}
*/
function List(config) {
this.config = config;
this.props = config.props;
this.main = config.main;
this.selectedLine = -2;
this.lines = [];
if (!config.getItems) {
config.getItems = function() {
return config.items;
}
}
if (!config.getItemProp) {
config.getItemProp = function(id, prop) {
return config.getItem(id)[prop];
}
}
if (!config.setItemProp) {
config.setItemProp = function(id, prop, value) {
config.getItem(id)[prop] = value;
}
}
if (!config.getItem) {
config.getItem = function(id) {
return config.getItems()[id];
}
}
if (!config.move) {
config.move = function(a, b) {
if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) {
var list = config.getItems();
var tmp = list[a];
// remove a
list.splice(a, 1);
// insert b
list.splice(b, 0, tmp);
}
}
};
if (!config.insert) {
config.insert = function(id, newItem) {
config.getItems().splice(id, 0, newItem);
}
}
if (!config.remove) {
config.remove = function(a) {
config.move(a, config.count() - 1);
config.getItems().pop();
}
}
if (!config.validate) {
config.validate = function() {return true;};
}
if (!config.count) {
config.count = function() {
return config.getItems().length;
}
}
if (!config.patch) {
config.patch = function(id, newVal) {
for (var name in newVal) {
config.setItemProp(id, name, newVal[name]);
}
}
}
if (!config.defaultValue) {
config.defaultValue = {};
}
config.main.addClass('list');
}
List.ids = {
noline: -1,
};
List.types = {};
List.prototype = {
init: function() {
with (this) {
if (this.inited) {
return;
}
this.inited = true;
this.headergroup = $('<div class="headers"></div>');
for (var i = 0; i < props.length; ++i) {
var header = $('<div class="header"></div>').
attr('property', props[i].property).html(props[i].header);
headergroup.append(header);
}
this.scrolls = $('<div>').addClass('listscroll');
this.contents = $('<div class="listitems"></div>').appendTo(scrolls);
scrolls.scroll(function() {
headergroup.css('left', -(scrolls.scrollLeft()) + 'px');
});
contents.click(function(e) {
if (e.target == contents[0]) {
selectLine(List.ids.noline);
}
});
$(main).append(headergroup).append(scrolls);
var height = this.main.height() - this.headergroup.outerHeight();
this.scrolls.height(height);
load();
selectLine(List.ids.noline);
}
},
editNewLine: function() {
this.startEdit(this.lines[this.lines.length - 1]);
},
updatePropDisplay : function(line, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var id = Number(line.attr('row'));
if (id == this.config.count()) {
var value = this.config.defaultValue[name];
if (value) {
ctrl.value = value;
}
obj.trigger('createNew');
} else {
ctrl.value = this.config.getItemProp(id, name);
obj.trigger('update');
}
},
updateLine: function(line) {
for (var i = 0; i < this.props.length; ++i) {
this.updatePropDisplay(line, this.props[i]);
}
if (Number(line.attr('row')) < this.config.count()) {
line.trigger('update');
} else {
line.addClass('newline');
}
},
createLine: function() {
with (this) {
var line = $('<div></div>').addClass('itemline');
var inner = $('<div>');
line.append(inner);
// create input boxes
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
var ctrl = $('<div></div>').attr('property', prop.property)
.addClass('listvalue').attr('tabindex', -1);
var valueobj = new List.types[prop.type](ctrl, prop);
var data = {list: this, line: line, prop: prop};
for (var e in prop.events) {
ctrl.bind(e, data, prop.events[e]);
}
ctrl.bind('change', function(e) {
validate(line);
return true;
});
ctrl.bind('keyup', function(e) {
if (e.keyCode == 27) {
cancelEdit(line);
}
});
ctrl.trigger('create');
inner.append(ctrl);
}
// Event listeners
line.click(function(e) {
startEdit(line);
});
line.focusin(function(e) {
startEdit(line);
});
line.focusout(function(e) {
finishEdit(line);
});
for (var e in this.config.lineEvents) {
line.bind(e, {list: this, line: line}, this.config.lineEvents[e]);
}
var list = this;
line.bind('updating', function() {
$(list).trigger('updating');
});
line.bind('updated', function() {
$(list).trigger('updated');
});
this.bindId(line, this.lines.length);
this.lines.push(line);
line.appendTo(this.contents);
return line;
}
},
refresh: function(lines) {
var all = false;
if (lines === undefined) {
all = true;
lines = [];
}
for (var i = this.lines.length; i <= this.config.count(); ++i) {
var line = this.createLine();
lines.push(i);
}
while (this.lines.length > this.config.count() + 1) {
this.lines.pop().remove();
}
$('.newline', this.contents).removeClass('newline');
this.lines[this.lines.length - 1].addClass('newline');
if (all) {
for (var i = 0; i < this.lines.length; ++i) {
this.updateLine(this.lines[i]);
}
} else {
for (var i = 0; i < lines.length; ++i) {
this.updateLine(this.lines[lines[i]]);
}
}
},
load: function() {
this.contents.empty();
this.lines = [];
this.refresh();
},
bindId: function(line, id) {
line.attr('row', id);
},
getLineNewValue: function(line) {
var ret = {};
for (var i = 0; i < this.props.length; ++i) {
this.getPropValue(line, ret, this.props[i]);
}
return ret;
},
getPropValue: function(line, item, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var value = ctrl.value;
if (value !== undefined) {
item[name] = value;
}
return value;
},
startEdit: function(line) {
if (line.hasClass('editing')) {
return;
}
line.addClass('editing');
this.showLine(line);
this.selectLine(line);
var list = this;
setTimeout(function() {
if (!line[0].contains(document.activeElement)) {
$('.valinput', line).first().focus();
}
list.validate(line);
}, 50);
},
finishEdit: function(line) {
var list = this;
function doFinishEdit() {
with(list) {
if (line[0].contains(document.activeElement)) {
return;
}
var valid = isValid(line);
if (valid) {
var id = Number(line.attr('row'));
var newval = getLineNewValue(line);
if (line.hasClass('newline')) {
$(list).trigger('updating');
if(!config.insert(id, newval)) {
line.removeClass('newline');
list.selectLine(line);
$(list).trigger('add', id);
addNewLine();
}
} else {
line.trigger('updating');
config.patch(id, newval);
}
line.trigger('updated');
}
cancelEdit(line);
}
};
setTimeout(doFinishEdit, 50);
},
cancelEdit: function(line) {
line.removeClass('editing');
line.removeClass('error');
var id = Number(line.attr('row'));
if (id == this.config.count() && this.selectedLine == id) {
this.selectedLine = List.ids.noline;
}
this.updateLine(line);
},
addNewLine: function() {
with(this) {
var line = $('.newline', contents);
if (!line.length) {
line = createLine().addClass('newline');
}
return line;
}
},
isValid: function(line) {
var id = Number(line.attr('row'));
var obj = this.getLineNewValue(line);
return valid = this.config.validate(id, obj);
},
validate: function(line) {
if (this.isValid(line)) {
line.removeClass('error');
} else {
line.addClass('error');
}
},
move: function(a, b, keepSelect) {
var len = this.config.count();
if (a == b || a < 0 || b < 0 || a >= len || b >= len) {
return;
}
this.config.move(a, b);
for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) {
this.updateLine(this.getLine(i));
}
if (keepSelect) {
if (this.selectedLine == a) {
this.selectLine(b);
} else if (this.selectedLine == b) {
this.selectLine(a);
}
}
},
getLine: function(id) {
if (id < 0 || id >= this.lines.length) {
return null;
}
return this.lines[id];
},
remove: function(id) {
id = Number(id);
if (id < 0 || id >= this.config.count()) {
return;
}
$(this).trigger('updating');
var len = this.lines.length;
this.getLine(id).trigger('removing');
if (this.config.remove(id)) {
return;
}
this.getLine(len - 1).remove();
this.lines.pop();
for (var i = id; i < len - 1; ++i) {
this.updateLine(this.getLine(i));
}
if (id >= len - 2) {
this.selectLine(id);
} else {
this.selectLine(List.ids.noline);
}
$(this).trigger('updated');
},
selectLine: function(id) {
var line = id;
if (typeof id == "number") {
line = this.getLine(id);
} else {
id = Number(line.attr('row'));
}
// Can't select the new line.
if (line && line.hasClass('newline')) {
line = null;
id = List.ids.noline;
}
if (this.selectedLine == id) {
return;
}
var oldline = this.getLine(this.selectedLine);
if (oldline) {
this.cancelEdit(oldline);
oldline.removeClass('selected');
oldline.trigger('deselect');
this.selectedLine = List.ids.noline;
}
this.selectedLine = id;
if (line != null) {
line.addClass('selected');
line.trigger('select');
this.showLine(line);
}
$(this).trigger('select');
},
showLine: function(line) {
var showtop = this.scrolls.scrollTop();
var showbottom = showtop + this.scrolls.height();
var top = line.offset().top - this.contents.offset().top;
// Include the scroll bar
var bottom = top + line.height() + 20;
if (top < showtop) {
// show at top
this.scrolls.scrollTop(top);
} else if (bottom > showbottom) {
// show at bottom
this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height()));
}
}
};
| 007slmg-np-activex-justep | web/list.js | JavaScript | mpl11 | 11,700 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var baseDir = '/setting/';
var rules = [];
var scripts = [];
var issues = [];
var dirty = false;
function setScriptAutoComplete(e) {
var last = /[^\s]*$/;
var obj = $('input', e.target);
$(obj).bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
scriptItems, last.exec(request.term)[0]));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
this.value = this.value.replace(last, ui.item.value);
return false;
}
});
}
var ruleProps = [ {
header: "Identifier",
property: "identifier",
type: "input"
}, {
header: "Name",
property: "title",
type: "input"
}, {
header: "Mode",
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: "WildChar"},
{value: "regex", text: "RegEx"},
{value: "clsid", text: "CLSID"}
]
}, {
header: "Pattern",
property: "value",
type: "input"
}, {
header: "Keyword",
property: "keyword",
type: "input"
}, {
header: "testURL",
property: "testUrl",
type: "input"
}, {
header: "UserAgent",
property: "userAgent",
type: "select",
option: "static",
options: [
{value: "", text: "Chrome"},
{value: "ie9", text: "MSIE9"},
{value: "ie8", text: "MSIE8"},
{value: "ie7", text: "MSIE7"},
{value: "ff7win", text: "Firefox 7 Windows"},
{value: "ff7mac", text: "Firefox 7 Mac"},
{value: "ip5", text: "iPhone"},
{value: "ipad5", text: "iPad"}
]
}, {
header: "Helper Script",
property: "script",
type: "input",
events: {
create: setScriptAutoComplete
}
}];
var currentScript = -1;
function showScript(id) {
var url = baseDir + scripts[id].url;
currentScript = id;
$(scriptEditor).val('');
$.ajax(url, {
success: function(value) {
origScript = value;
$(scriptEditor).val(value);
}
});
$('#scriptDialog').dialog('open');
}
function saveToFile(file, value) {
$.ajax(baseDir + 'upload.php', {
type: "POST",
data: {
file: file,
data: value
}
});
}
var origScript;
function saveScript(id) {
var value = $('#scriptEditor').val();
if (value == origScript) {
return;
}
var file = scripts[id].url;
scriptList.updateLine(scriptList.getLine(id));
saveToFile(file, value);
dirty = true;
}
var scriptProps = [{
property: "identifier",
header: "Identifier",
type: "input"
}, {
property: "url",
header: "URL",
type: "input"
}, {
property: "context",
header: "Context",
type: "select",
option: "static",
options: [
{value: "page", text: "Page"},
{value: "extension", text: "Extension"}
]
}, {
property: "show",
header: "Show",
type: "button",
events: {
create: function(e) {
$('button', this).text('Show');
},
command: function(e) {
showScript(Number(e.data.line.attr('row')), true);
}
}
}];
var issueProps = [{
header: "Identifier",
property: "identifier",
type: "input"
}, {
header: "Mode",
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: "WildChar"},
{value: "regex", text: "RegEx"},
{value: "clsid", text: "CLSID"}
]
}, {
header: "Pattern",
property: "value",
type: "input"
}, {
header: "Description",
property: "description",
type: "input"
}, {
header: "IssueId",
property: "issueId",
type: "input"
}, {
header: "url",
property: "url",
type: "input"
}];
// The JSON formatter is from http://joncom.be/code/javascript-json-formatter/
function FormatJSON(oData, sIndent) {
function RealTypeOf(v) {
if (typeof(v) == "object") {
if (v === null) return "null";
if (v.constructor == Array) return "array";
if (v.constructor == Date) return "date";
if (v.constructor == RegExp) return "regex";
return "object";
}
return typeof(v);
}
if (arguments.length < 2) {
var sIndent = "";
}
var sIndentStyle = " ";
var sDataType = RealTypeOf(oData);
// open object
if (sDataType == "array") {
if (oData.length == 0) {
return "[]";
}
var sHTML = "[";
} else {
var iCount = 0;
$.each(oData, function() {
iCount++;
return;
});
if (iCount == 0) { // object is empty
return "{}";
}
var sHTML = "{";
}
// loop through items
var iCount = 0;
$.each(oData, function(sKey, vValue) {
if (iCount > 0) {
sHTML += ",";
}
if (sDataType == "array") {
sHTML += ("\n" + sIndent + sIndentStyle);
} else {
sHTML += ("\n" + sIndent + sIndentStyle + "\"" + sKey + "\"" + ": ");
}
// display relevant data type
switch (RealTypeOf(vValue)) {
case "array":
case "object":
sHTML += FormatJSON(vValue, (sIndent + sIndentStyle));
break;
case "boolean":
case "number":
sHTML += vValue.toString();
break;
case "null":
sHTML += "null";
break;
case "string":
sHTML += ("\"" + vValue + "\"");
break;
default:
sHTML += JSON.stringify(vValue);
}
// loop
iCount++;
});
// close object
if (sDataType == "array") {
sHTML += ("\n" + sIndent + "]");
} else {
sHTML += ("\n" + sIndent + "}");
}
// return
return sHTML;
}
function loadRules(value) {
rules = [];
for (var i in value) {
rules.push(value[i]);
}
ruleList.refresh();
freezeIdentifier(ruleList);
}
function loadIssues(value) {
issues = [];
for (var i in value) {
issues.push(value[i]);
}
issueList.refresh();
freezeIdentifier(issueList);
}
function loadScripts(value) {
scripts = [];
for (var i in value) {
scripts.push(value[i]);
}
scriptList.refresh();
freezeIdentifier(scriptList);
updateScriptItems();
}
function serialize(list) {
var obj = {};
for (var i = 0; i < list.length; ++i) {
obj[list[i].identifier] = list[i];
}
return FormatJSON(obj);
}
function save() {
saveToFile('setting.json', serialize(rules));
saveToFile('scripts.json', serialize(scripts));
saveToFile('issues.json', serialize(issues));
dirty= false;
freezeIdentifier(ruleList);
freezeIdentifier(scriptList);
}
function reload() {
$.ajax(baseDir + 'setting.json', {
success: loadRules
});
$.ajax(baseDir + 'scripts.json', {
success: loadScripts
});
$.ajax(baseDir + 'issues.json', {
success: loadIssues
});
dirty = false;
}
function freezeIdentifier(list) {
$('.itemline:not(.newline) div[property=identifier]', list.contents)
.addClass('readonly');
}
var scriptList, ruleList, issueList;
var scriptItems = [];
function updateScriptItems() {
scriptItems = [];
for (var i = 0; i < scripts.length; ++i) {
scriptItems.push(scripts[i].identifier);
}
}
$(document).ready(function() {
window.onbeforeunload=function() {
if (dirty) {
return 'Page not saved. Continue?';
}
}
$('#addRule').click(function() {
ruleList.editNewLine();
}).button();
$('#deleteRule').click(function() {
ruleList.remove(ruleList.selectedLine);
}).button();
$('#addScript').click(function() {
scriptList.editNewLine();
}).button();
$('#deleteScript').click(function() {
scriptList.remove(scriptList.selectedLine);
}).button();
$('#addIssue').click(function() {
issueList.editNewLine();
}).button();
$('#deleteIssue').click(function() {
issueList.remove(issueList.selectedLine);
}).button();
$('.doSave').each(function() {
$(this).click(save).button();
});
$('#tabs').tabs();
$('#scriptDialog').dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
"Save": function() {
saveScript(currentScript);
$(this).dialog('close');
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
$.ajaxSetup({
cache: false
});
scriptList = new List({
props: scriptProps,
main: $('#scriptTable'),
getItems: function() {return scripts;}
});
$(scriptList).bind('updated', function() {
dirty = true;
updateScriptItems();
});
scriptList.init();
ruleList = new List({
props: ruleProps,
main: $('#ruleTable'),
getItems: function() {return rules;}
});
ruleList.init();
$(ruleList).bind('updated', function() {
dirty = true;
});
issueList = new List({
props: issueProps,
main: $('#issueTable'),
getItems: function() {return issues;}
});
issueList.init();
$(issueList).bind('updated', function() {
dirty = true;
});
reload();
});
| 007slmg-np-activex-justep | web/editor.js | JavaScript | mpl11 | 9,473 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta>
<style>
.line {
clear: both;
margin: 4px 0px;
}
.item {
margin: 4px 3px;
float: left;
}
</style>
<script>
var link = "https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn"
var text = '在Chrome中直接使用各类网银、快播等ActiveX控件,无需使用IE Tab等IE内核插件!数万用户的实践验证!点击链接下载';
</script>
</head>
<body>
<div id="header" style="height:100px">
</div>
<div class="line">
<!-- Place this tag where you want the +1 button to render -->
<g:plusone annotation="inline" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn"></g:plusone>
<!-- Place this render call where appropriate -->
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</div>
<div class="line">
<div class="item">
<script type="text/javascript" charset="utf-8">
(function(){
var _w = 106 , _h = 24;
var param = {
url:link,
type:'5',
count:'', /**是否显示分享数,1显示(可选)*/
appkey:'', /**您申请的应用appkey,显示分享来源(可选)*/
title:text,
pic:'', /**分享图片的路径(可选)*/
ralateUid:'2356524070', /**关联用户的UID,分享微博会@该用户(可选)*/
language:'zh_cn', /**设置语言,zh_cn|zh_tw(可选)*/
rnd:new Date().valueOf()
}
var temp = [];
for( var p in param ){
temp.push(p + '=' + encodeURIComponent( param[p] || '' ) )
}
document.write('<iframe allowTransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?' + temp.join('&') + '" width="'+ _w+'" height="'+_h+'"></iframe>')
})()
</script>
</div>
<div class="item">
<a name="xn_share" type="button_count_right" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn/">分享到人人</a><script src="http://static.connect.renren.com/js/share.js" type="text/javascript"></script></div>
<div class="item">
<a href="javascript:void(0)" onclick="postToWb();return false;" class="tmblog"><img src="http://v.t.qq.com/share/images/s/b24.png" border="0" alt="转播到腾讯微博" ></a><script type="text/javascript">
function postToWb(){
var _url = encodeURIComponent(link);
var _assname = encodeURI("");//你注册的帐号,不是昵称
var _appkey = encodeURI("");//你从腾讯获得的appkey
var _pic = encodeURI('');//(例如:var _pic='图片url1|图片url2|图片url3....)
var _t = '';//标题和描述信息
var metainfo = document.getElementsByTagName("meta");
for(var metai = 0;metai < metainfo.length;metai++){
if((new RegExp('description','gi')).test(metainfo[metai].getAttribute("name"))){
_t = metainfo[metai].attributes["content"].value;
}
}
_t = text;
if(_t.length > 120){
_t= _t.substr(0,117)+'...';
}
_t = encodeURI(_t);
var _u = 'http://share.v.t.qq.com/index.php?c=share&a=index&url='+_url+'&appkey='+_appkey+'&pic='+_pic+'&assname='+_assname+'&title='+_t;
window.open( _u,'', 'width=700, height=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no' );
}
</script>
</div>
</div>
<div id="footer" style="height:100px;clear:both">
</div>
</body>
</html>
| 007slmg-np-activex-justep | web/share.html | HTML | mpl11 | 3,718 |
<html>
<head>
<link rel="stylesheet" type="text/css" href="list.css" />
<link rel="stylesheet" type="text/css" href="editor.css" />
<link type="text/css" href="jquery-ui-1.8.17.custom.css" rel="stylesheet" />
<script src="jquery-1.7.min.js"></script>
<script src="jquery-ui-1.8.17.custom.min.js"></script>
<script src="list.js"></script>
<script src="listtypes.js"></script>
<script src="editor.js"></script>
</head>
<body>
<div id="tabs">
<ul>
<li><a href="#rules">Rules</a></li>
<li><a href="#scripts">Scripts</a></li>
<li><a href="#issues">Issues</a></li>
</ul>
<div id="rules">
<div id="ruleTable">
</div>
<div>
<button id="addRule">Add</button>
<button id="deleteRule">Delete</button>
<button class="doSave">Save</button>
</div>
</div>
<div id="scripts">
<div id="scriptTable">
</div>
<div>
<button id="addScript">Add</button>
<button id="deleteScript">Delete</button>
<button class="doSave">Save</button>
</div>
</div>
<div id="issues">
<div id="issueTable">
</div>
<div>
<button id="addIssue">Add</button>
<button id="deleteIssue">Delete</button>
<button class="doSave">Save</button>
</div>
</div>
</div>
<div id="scriptDialog">
<textarea id="scriptEditor"></textarea>
</div>
</body>
</html>
| 007slmg-np-activex-justep | web/editor.html | HTML | mpl11 | 1,570 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
List.types.input = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input></input>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
this.input.focus(function(e) {
input.select();
});
this.input.keypress(function(e) {
p.trigger('change');
});
this.input.keyup(function(e) {
p.trigger('change');
});
this.input.change(function(e) {
p.trigger('change');
});
p.append(this.input).append(this.label);
};
List.types.input.prototype.__defineSetter__('value', function(val) {
this.input.val(val);
this.label.text(val);
});
List.types.input.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<select></select>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
if (prop.option == 'static') {
this.loadOptions(prop.options);
}
var select = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
select.value = select.lastval;
} else {
p.trigger('change');
}
});
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
p.append(this.input).append(this.label);
};
List.types.select.prototype.loadOptions = function(options) {
this.options = options;
this.mapping = {};
this.input.html("");
for (var i = 0; i < options.length; ++i) {
this.mapping[options[i].value] = options[i].text;
var o = $('<option></option>').val(options[i].value).text(options[i].text)
this.input.append(o);
}
}
List.types.select.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input.val(val);
this.label.text(this.mapping[val]);
});
List.types.checkbox = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input type="checkbox">').addClass('valcheck');
var box = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
box.value = box.lastval;
} else {
p.trigger('change');
}
});
p.append(this.input);
};
List.types.checkbox.prototype.__defineGetter__('value', function() {
return this.input[0].checked;
});
List.types.checkbox.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input[0].checked = val;
});
List.types.button = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<button>');
if (prop.caption) {
input.text(prop.caption);
}
input.click(function(e) {
p.trigger('command');
return false;
});
p.append(this.input);
};
List.types.button.prototype.__defineGetter__('value', function() {
return undefined;
});
| 007slmg-np-activex-justep | web/listtypes.js | JavaScript | mpl11 | 3,295 |
import urllib
import urllib2
import argparse
import sys
from log import Logger
from datetime import datetime, timedelta
def verify_order(postdata, sandbox):
data = 'cmd=_notify-validate&' + postdata
if sandbox:
scr = 'https://www.sandbox.paypal.com/cgi-bin/websc'
else:
scr = 'https://www.paypal.com/cgi-bin/websc'
res = urllib2.urlopen(scr, data).read()
if res == 'VERIFIED':
return True
return False
def convert_order(item):
value = {}
value['name'] = item['address_name']
value['mail'] = item['payer_email']
value['nickname'] = item['address_name']
gross = float(item['mc_gross'])
fee = float(item['mc_fee'])
value['amount'] = gross
value['actual_amount'] = gross - fee
value['unit'] = 'USD'
value['comment'] = ''
try:
value['time'] = datetime.strptime(
item['payment_date'], '%H:%M:%S %b %d, %Y PDT') + timedelta(hours = 15)
except:
value['time'] = datetime.strptime(
item['payment_date'], '%H:%M:%S %b %d, %Y PST') + timedelta(hours = 16)
value['method'] = 'paypal'
value['id'] = item['txn_id']
return value
def get_order(postdata):
fields = postdata.split('&')
item = {}
for field in fields:
name, value = field.split('=')
value = urllib.unquote_plus(value)
item[name] = value
for field in item:
item[field] = item[field].decode(item['charset'])
return item
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--log', dest='logfile', help='Logfile',
required=True)
parser.add_argument('-p', '--paypal', dest='paypal', help='Paypal input',
required=True)
args = parser.parse_args()
item = get_order(args.paypal)
if not verify_order(args.paypal, 'test_ipn' in item):
print 'Error in verification'
print args.paypal
sys.exit(1)
if item['payment_status'] != 'Completed':
print 'Payment from ', item['address_name'], ' not completed ', item['txn_id']
print args.paypal
sys.exit(1)
logitem = convert_order(item)
logfile = args.logfile
if 'test_ipn' in item:
logfile = 'test'
logger = Logger({'logfile': logfile})
logger.log(logitem)
logger.close()
print (u'Received payment from %s, txn_id=%s, amount=$%.2f, date=%s' % (
logitem['name'], logitem['id'], logitem['amount'], item['payment_date']
)).encode('utf-8')
if __name__ == '__main__':
main()
| 007slmg-np-activex-justep | Tools/donation/paypal.py | Python | mpl11 | 2,448 |
import threading
import os
import csv
import argparse
from datetime import datetime
class Logger:
fields = ['name', 'mail', 'nickname', 'amount', 'actual_amount', 'unit',\
'comment', 'time', 'method', 'id']
def __init__(self, config):
logfile = config['logfile']
self.path = logfile + '.csv'
self.amount_file = logfile + '.sum'
self._file = open(self.path, 'ab', 1)
self._writer = csv.DictWriter(self._file, Logger.fields)
self._sum_lock = threading.RLock()
self.lock = threading.RLock()
try:
timestamp = os.stat(self.amount_file).st_mtime
except Exception as ex:
with open(self.amount_file, 'w') as f:
print '0\n0\n0' > f
timestamp = os.stat(self.amount_file).st_mtime
self.lastupdate = datetime.fromtimestamp(timestamp)
def log(self, item):
with self.lock:
s = dict(item)
s['time'] = s['time'].strftime('%Y/%m/%d %H:%M:%S')
for i in s:
if isinstance(s[i], unicode):
s[i] = s[i].encode('utf-8')
self._writer.writerow(s)
if item['unit'] == 'RMB':
self.add_total(0, 0, float(item['amount']))
else:
self.add_total(float(item['amount']), float(item['actual_amount']), 0)
def close(self):
self._file.close()
def read_total(self):
with self._sum_lock:
val = []
with open(self.amount_file) as amount_file:
for line in amount_file:
val.append(float(line))
return val
def read_records(self):
with self.lock:
self._file.close()
f = open(self.path, 'rb')
reader = csv.DictReader(f, Logger.fields)
# Read the header
vals = []
for item in reader:
item['time'] = datetime.strptime(item['time'], '%Y/%m/%d %H:%M:%S')
item['amount'] = float(item['amount'])
item['actual_amount'] = float(item['actual_amount'])
for field in item:
value = item[field]
if isinstance(value, str):
item[field] = value.decode('utf-8')
vals.append(item)
vals.sort(key = lambda x : x['time'])
self._file = open(self.path, 'ab', 1)
self._writer = csv.DictWriter(self._file, Logger.fields)
return vals
def add_total(self, *delta):
with self._sum_lock:
val = self.read_total()
for i in xrange(len(delta)):
val[i] += delta[i]
with open(self.amount_file, 'w') as amount_file:
for v in val:
print >> amount_file, v
def add_from_input(self):
item = {}
print '1: paypal'
print '2: taobao'
print '3: alipay'
method = int(raw_input('Select the payment method:'))
method = ['paypal', 'taobao', 'alipay'][method - 1]
item['method'] = method
if method == 'paypal':
item['unit'] = 'USD'
else:
item['unit'] = 'RMB'
for field in Logger.fields:
if field == 'actual_amount':
if method in ['taobao', 'alipay']:
item['actual_amount'] = item['amount']
else:
item['actual_amount'] = float(raw_input(field + ':'))
elif field == 'amount':
item[field] = float(raw_input(field + ':'))
elif field == 'time':
if method == 'paypal':
fmt = '%Y-%b-%d %H:%M:%S'
else:
fmt = '%Y-%m-%d %H:%M:%S'
item[field] = datetime.strptime(raw_input(field + ':'), fmt)
elif field in ['method', 'unit']:
pass
elif field == 'nickname' and method != 'taobao':
item[field] = item['name']
else:
item[field] = unicode(raw_input(field + ':'), 'gbk')
self.log(item)
print 'item added'
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--log', dest='logfile', help='Logfile',
required=True)
args = parser.parse_args()
logger = Logger(vars(args))
while True:
logger.add_from_input()
if raw_input('continue(y/N)?') != 'y':
break
logger.close()
if __name__ == '__main__':
main()
| 007slmg-np-activex-justep | Tools/donation/log.py | Python | mpl11 | 4,082 |
import sys
import top.api as topapi
import traceback
import log
import top
import json
import re
import webbrowser
import time
import urllib2
import cookielib
import urllib
import httplib
from ConfigParser import ConfigParser
from datetime import datetime, timedelta
class T:
def trace_exception(self, ex):
print ex
common = T()
configfile = 'config'
class TaobaoBackground:
def __init__(self, config):
self.config = config
self.onNewPaidOrder = []
self.onConfirmedOrder = []
self.retry = 1
self.stream = None
def get_permit(self):
request = self.config.create_request(topapi.IncrementCustomerPermitRequest)
request.session = self.config.session
f = request.getResponse()
print 'increment permit ', f
def start_stream(self):
site = self.config.stream_site
data = {}
data['app_key'] = self.config.appinfo.appkey
time = datetime.utcnow()
time += timedelta(hours = 8)
data['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
data['sign'] = top.sign(self.config.appinfo.secret, data)
url = '/stream'
self.connection = httplib.HTTPConnection(site, 80, timeout=60)
self.connection.request('POST', url, urllib.urlencode(data), self.get_request_header())
self.stream = self.connection.getresponse()
def get_request_header(self):
return {
'Content-type': 'application/x-www-form-urlencoded',
"Cache-Control": "no-cache",
"Connection": "Keep-Alive",
}
def start(self):
# get permit
self.get_permit()
self.start_stream()
def getMessage(self):
text = ''
while True:
char = self.stream.read(1)
if char == '\r':
continue
if char == '\n':
break
text += char
return json.loads(text)['packet']
def run(self):
self.start()
while True:
msg = self.getMessage()
self.processMessage(msg)
def processMessage(self, msg):
if msg['code'] == 101:
retry = 1
elif msg['code'] == 102:
retry = msg['msg']
elif msg['code'] == 103:
retry = msg['msg']
elif msg['code'] == 200:
print msg['msg']
elif msg['code'] == 203:
print 'Data lost'
self.config.pull(msg['msg']['begin'] / 1000, msg['msg']['end'] / 1000)
elif msg['code'] == 202:
# data
print msg['msg']
class TaobaoAx:
def __init__(self, configParser, logger):
self.session = None
self.sessionTs = 0
self.freq = 30
self.configParser = configParser
self._tradefields = 'buyer_nick,num_iid,status,pay_time,tid,payment,seller_rate,has_buyer_message,buyer_message,buyer_email,receiver_name'
self.logger = logger
def read_config(self):
cp = self.configParser
self.session = cp.get('taobao', 'session')
self.sessionTs = cp.getfloat('taobao', 'expire')
self.sessionTime = datetime.fromtimestamp(self.sessionTs)
appkey = cp.get('taobao', 'appkey')
secret = cp.get('taobao', 'appsecret')
self.appinfo = top.appinfo(appkey, secret)
self.site = cp.get('taobao', 'appsite')
self.authurl = cp.get('taobao', 'auth_url')
self.tokenurl = cp.get('taobao', 'token_url')
self.stream_site = cp.get('taobao', 'stream_site')
self.freq = cp.getint('taobao', 'freq');
if self.sessionTime > datetime.now():
print 'loaded session ', self.session
def write_config(self):
cp = self.configParser
cp.set('taobao', 'session', self.session)
cp.set('taobao', 'expire', self.sessionTs)
cp.set('taobao', 'freq', self.freq);
o = open(configfile, 'w')
cp.write(o)
o.close()
def get_auth_code(self):
if len(sys.argv) > 1:
return sys.argv[1];
url = self.authurl + str(self.appinfo.appkey)
webbrowser.open(url)
return raw_input("session authentication reqired:\n")
def request_session(self):
authcode = self.get_auth_code()
authurl = self.tokenurl
request = {}
request['client_id'] = self.appinfo.appkey
request['client_secret'] = self.appinfo.secret
request['grant_type'] = 'authorization_code'
request['code'] = authcode
request['redirect_uri'] = 'urn:ietf:wg:oauth:2.0:oob'
requeststr = urllib.urlencode(request)
response = urllib2.urlopen(authurl, requeststr).read()
response = json.loads(response)
print response
self.sessionTs = time.time() + response['expires_in']
self.sessionTime = datetime.fromtimestamp(self.sessionTs)
self.session = response['access_token']
#self.write_config()
nick = unicode(urllib2.unquote(str(response['taobao_user_nick'])), 'utf-8')
print 'Successfully logged in'
def init(self):
try:
pass
except:
self.session = None
self.read_config()
if self.session == None or self.sessionTime < datetime.now():
self.request_session()
def send_good(self, order):
request = self.create_request(topapi.LogisticsDummySendRequest)
request.session = self.session
request.tid = order['tid']
result = request.getResponse()
print 'send good: ', order['payment'], order['buyer_nick'].encode("GBK")
def rate_order(self, order):
request = self.create_request(topapi.TraderateAddRequest)
request.session = self.session
request.tid = order['tid']
request.role = 'seller'
request.flag = 2
request.result = 'good'
request.getResponse()
print 'rate order: ', order['payment'], order['buyer_nick'].encode("GBK")
def memo_order(self, order):
request = self.create_request(topapi.TradeMemoUpdateRequest)
request.session = self.session
request.tid = order['tid']
request.memo = 'Send by taobao.py'
request.getResponse()
def log_order(self, order):
logitem = {}
logitem['name'] = order['receiver_name']
logitem['mail'] = order['buyer_email']
logitem['nickname'] = order['buyer_nick']
logitem['amount'] = float(order['payment'])
logitem['actual_amount'] = float(order['payment'])
logitem['unit'] = 'RMB'
logitem['comment'] = order['buyer_message']
logitem['time'] = order['pay_time']
logitem['method'] = 'taobao'
logitem['id'] = order['tid']
self.logger.log(logitem)
def process_order(self, orderid):
try:
order = self.get_full_info(orderid)
if order['status'] == 'WAIT_SELLER_SEND_GOODS':
self.send_good(order)
self.memo_order(order)
self.log_order(order)
elif order['status'] == 'TRADE_FINISHED' and not order['seller_rate']:
self.rate_order(order)
except topapi.base.TopException as ex:
traceback.print_exc()
common.trace_exception(ex)
except topapi.base.RequestException as ex:
traceback.print_exc()
common.trace_exception(ex)
def get_paid_orders(self):
request = self.create_request(topapi.TradesSoldGetRequest)
request.session = self.session
request.fields = 'tid'
request.page_size = 100
request.page_no = 1
request.type = 'guarantee_trade'
return self._load_all_orders(request)
def _load_all_orders(self, request):
request.use_has_next = True
orders = []
while True:
f = request.getResponse()['trades_sold_get_response']
if 'trades' in f:
orders += f['trades']['trade']
if f['has_next']:
request.page_no += 1
else:
break
return orders
def get_wait_rate_orders(self):
request = self.create_request(topapi.TradesSoldGetRequest)
request.session = self.session
request.fields = 'tid'
request.status = 'TRADE_FINISHED'
request.rate_status = 'RATE_UNSELLER'
request.start_created = datetime.now() - timedelta(days = 21)
request.page_size = 100
request.type = 'guarantee_trade'
return self._load_all_orders(request)
def get_new_orders(self):
request = self.create_request(topapi.TradesSoldGetRequest)
request.session = self.session
request.fields = 'tid'
request.status = 'WAIT_SELLER_SEND_GOODS'
request.start_created = datetime.now() - timedelta(days = 5)
request.type = 'guarantee_trade'
request.page_size = 100
request.use_has_next = True
return self._load_all_orders(request)
def query_and_process_orders(self):
new_orders = self.get_new_orders()
unrated_orders = self.get_wait_rate_orders()
for order in new_orders + unrated_orders:
self.process_order(order['tid'])
def run(self):
while True:
try:
self.query_and_process_orders()
except Exception, ex:
if isinstance(ex, top.api.base.TopException):
if ex.subcode == 'isv.trade-service-rejection':
print 'Error: isv.trade-service-rejection, pause 3 minutes'
time.sleep(3 * 60)
traceback.print_exc()
common.trace_exception(ex)
#time.sleep(self.freq)
raw_input()
def get_full_info(self, tradeid):
request = self.create_request(topapi.TradeFullinfoGetRequest)
request.session = self.session
request.fields = self._tradefields
request.tid = tradeid
trade = request.getResponse()['trade_fullinfo_get_response']['trade']
if not 'buyer_message' in trade:
trade['buyer_message'] = u''
if not 'buyer_email' in trade:
trade['buyer_email'] = u''
if 'pay_time' in trade:
trade['pay_time'] = datetime.strptime(
trade['pay_time'], '%Y-%m-%d %H:%M:%S')
else:
trade['pay_time'] = datetime.fromtimestamp(0)
return trade
def make_record(self):
trades = self.get_paid_orders()
f = open('trades.csv', 'w')
print >>f, self._tradefields
fields = self._tradefields.split(',')
trades.reverse()
sum = 0
for tradeid in trades:
trade = self.get_full_info(tradeid['tid'])
if trade['status'] not in ['WAIT_BUYER_PAY', 'TRADE_CLOSED_BY_TAOBAO']:
newtrade = dict(trade)
newtrade.setdefault('pay_time', '')
newtrade['tid'] = '="%s"' % trade['tid']
newtrade['num_iid'] = '="%s"' % trade['num_iid']
items = [newtrade.get(field, '') for field in fields]
for i in range(len(items)):
if not isinstance(items[i], basestring):
items[i] = str(items[i])
s = u','.join(items)
sum += float(trade['payment'])
print >>f, s.encode('gbk')
f.close()
print 'Total: ', sum
def run_background(self):
runner = TaobaoBackground(self)
runner.onNewPaidOrder += [self.on_new_order]
runner.onConfirmedOrder += [self.on_confirmed_order]
runner.run()
def on_confirmed_order(self, order):
self.evaluate_buyer(order)
def on_new_order(self, order):
self.process_order(order['tid'])
def create_request(self, requestType):
val = requestType(self.site, 80)
val.set_app_info(self.appinfo)
return val
def main():
cp = ConfigParser()
cp.read(configfile)
logger = log.Logger({'logfile': cp.get('log', 'logfile')})
instance = TaobaoAx(cp, logger)
instance.read_config()
instance.init()
instance.query_and_process_orders()
if __name__ == '__main__':
main()
| 007slmg-np-activex-justep | Tools/donation/taobao.py | Python | mpl11 | 11,377 |
from hgapi import *
import shutil
import os
import threading
import optparse
import traceback
import log
from datetime import datetime, timedelta
class HGDonationLog:
def __init__(self, config, logger):
self._path = config['path']
self._repo = Repo(self._path)
self._target = config['logfile']
self._templatefile = config['template']
self._update_interval = float(config.get('update_interval', 300))
self._logger = logger
self.lastupdate = datetime.fromtimestamp(0)
def start_listener(self):
self.thread = threading.Thread(target = self.listener_thread)
self.thread.start()
def listener_thread(self):
self.update_file()
while True:
sleep(self._update_interval)
lastdataupdate = logger.lastupdate()
if lastdataupdate > self.lastupdate:
self.update_file()
def gen_file(self, path):
with open(path, 'w') as f:
with open(self._templatefile, 'r') as tempfile:
template = tempfile.read().decode('utf-8')
usd, usdnofee, cny = self._logger.read_total()
chinatime = (datetime.utcnow() + timedelta(hours = 8))
lastupdatestr = chinatime.strftime('%Y-%b-%d %X') + ' GMT+8'
s = template.format(cny = cny, usd = usd, usdnofee = usdnofee, lastupdate = lastupdatestr)
f.write(s.encode('utf-8'))
records = self._logger.read_records()
records.reverse()
for item in records:
t = item['time'].strftime('%b %d, %Y')
item['datestr'] = t
s = u'|| {nickname} || {amount:.2f} {unit} || {datestr} ||'.format(**item)
print >>f, s.encode('utf-8')
def update_file(self):
try:
self._repo.hg_command('pull')
self._repo.hg_update(self._repo.hg_heads()[0])
path = os.path.join(self._path, self._target)
print 'update donation log on wiki at ', datetime.utcnow() + timedelta(hours=8)
self.gen_file(path)
print 'File generated'
msg = 'Auto update from script'
diff = self._repo.hg_command('diff', self._target)
if diff == '':
print 'No change, skipping update donation wiki'
return
else:
print diff.encode('utf-8')
self._repo.hg_commit(msg, files = [self._target])
print 'change committed'
self._repo.hg_command('push')
print 'repo pushed to server'
self.lastupdate = datetime.utcnow() + timedelta(hours = 8)
except Exception as ex:
print 'Update wiki failed: ', str(ex).encode('utf-8')
traceback.print_exc()
def main():
parser = optparse.OptionParser()
parser.add_option('-w', '--wiki', dest='path', help='Your wiki repo')
parser.add_option('-o', '--output', dest='logfile', help='Your logging file')
parser.add_option('-t', '--template', dest='template',
help='Your template file')
parser.add_option('-l', '--logfile', dest='log', help='Log file')
options, args = parser.parse_args()
logger = log.Logger({'logfile': options.log})
print vars(options)
hgclient = HGDonationLog(vars(options), logger)
hgclient.update_file()
if __name__ == '__main__':
main()
| 007slmg-np-activex-justep | Tools/donation/hg.py | Python | mpl11 | 3,178 |
import subprocess
import tempfile
import shutil
import os
import codecs
import json
import zipfile
class Packer:
def __init__(self, input_path, outputfile):
self.input_path = os.path.abspath(input_path)
self.outputfile = os.path.abspath(outputfile)
self.tmppath = None
def pack(self):
if self.tmppath == None:
self.tmppath = tempfile.mkdtemp()
else:
self.tmppath = os.path.abspath(self.tmppath)
if not os.path.isdir(self.tmppath):
os.mkdir(self.tmppath)
self.zipf = zipfile.ZipFile(self.outputfile, 'w', zipfile.ZIP_DEFLATED)
self.processdir('')
self.zipf.close()
def processdir(self, path):
dst = os.path.join(self.tmppath, path)
if not os.path.isdir(dst):
os.mkdir(dst)
for f in os.listdir(os.path.join(self.input_path, path)):
abspath = os.path.join(self.input_path, path, f)
if os.path.isdir(abspath):
self.processdir(os.path.join(path, f))
else:
self.processfile(os.path.join(path, f))
def compact_json(self, src, dst):
print 'Compacting json file ', src
with open(src) as s:
sval = s.read()
if sval[:3] == codecs.BOM_UTF8:
sval = sval[3:].decode('utf-8')
val = json.loads(sval, 'utf-8')
with open(dst, 'w') as d:
json.dump(val, d, separators=(',', ':'))
def processfile(self, path):
src = os.path.join(self.input_path, path)
dst = os.path.join(self.tmppath, path)
if not os.path.isfile(dst) or os.stat(src).st_mtime > os.stat(dst).st_mtime:
ext = os.path.splitext(path)[1].lower()
op = None
if ext == '.js':
if path.split(os.sep)[0] == 'settings':
op = self.copyfile
elif os.path.basename(path) == 'jquery.js':
op = self.copyfile
else:
op = self.compilefile
elif ext == '.json':
op = self.compact_json
elif ext in ['.swp', '.php']:
pass
else:
op = self.copyfile
if op != None:
op(src, dst)
if os.path.isfile(dst):
self.zipf.write(dst, path)
def copyfile(self, src, dst):
shutil.copyfile(src, dst)
def compilefile(self, src, dst):
args = ['java', '-jar', 'compiler.jar',\
'--js', src, '--js_output_file', dst]
args += ['--language_in', 'ECMASCRIPT5']
print 'Compiling ', src
retval = subprocess.call(args)
if retval != 0:
os.remove(dst)
print 'Failed to generate ', dst
a = Packer('..\\chrome', '..\\plugin.zip')
a.tmppath = '..\\output'
a.pack()
| 007slmg-np-activex-justep | Tools/pack.py | Python | mpl11 | 2,602 |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
if user_name is None or password is None:
from netrc import netrc
authenticators = netrc().authenticators("code.google.com")
if authenticators:
if user_name is None:
user_name = authenticators[0]
if password is None:
password = authenticators[2]
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| 007slmg-np-activex-justep | Tools/googlecode_upload.py | Python | mpl11 | 9,200 |
# Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
# Use of this source code is governed by a Mozilla-1.1 license that can be
# found in the LICENSE file.
import googlecode_upload
import tempfile
import urllib2
import optparse
import os
extensionid = 'lgllffgicojgllpmdbemgglaponefajn'
def download():
url = ("https://clients2.google.com/service/update2/crx?"
"response=redirect&x=id%3D" + extensionid + "%26uc")
response = urllib2.urlopen(url)
filename = response.geturl().split('/')[-1]
version = '.'.join(filename.replace('_', '.').split('.')[1:-1])
name = os.path.join(tempfile.gettempdir(), filename)
f = open(name, 'wb')
data = response.read()
f.write(data)
f.close()
return name, version
def upload(path, version, user, password):
summary = 'Extension version ' + version + ' download'
labels = ['Type-Executable']
print googlecode_upload.upload(
path, 'np-activex', user, password, summary, labels)
def main():
parser = optparse.OptionParser()
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
options, args = parser.parse_args()
name, version = download()
print 'File downloaded ', name, version
upload(name, version, options.user, options.password)
os.remove(name)
if __name__ == '__main__':
main()
| 007slmg-np-activex-justep | Tools/upload.py | Python | mpl11 | 1,501 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <npruntime.h>
#include <npapi.h>
#include "npactivex.h"
class NPVariantProxy : public NPVariant
{
public:
NPVariantProxy() {
VOID_TO_NPVARIANT(*this);
}
~NPVariantProxy() {
NPNFuncs.releasevariantvalue(this);
}
};
class NPObjectProxy {
private:
NPObject *object;
public:
NPObjectProxy() {
object = NULL;
}
NPObjectProxy(NPObject *obj) {
object = obj;
}
void reset() {
if (object)
NPNFuncs.releaseobject(object);
object = NULL;
}
~NPObjectProxy() {
reset();
}
operator NPObject*&() {
return object;
}
NPObjectProxy& operator =(NPObject* obj) {
reset();
object = obj;
return *this;
}
}; | 007slmg-np-activex-justep | ffactivex/objectProxy.h | C++ | mpl11 | 2,216 |
comment ?
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
?
.386
.model flat
PUBLIC _DualProcessCommandWrap
_DualProcessCommand proto
.code
_DualProcessCommandWrap proc
push 0
call _DualProcessCommand
; Thanks god we can use ecx, edx for free
pop ecx ; length of par
pop edx ; command id
pop edx ; return address
add esp, ecx
jmp edx
_DualProcessCommandWrap endp
end
| 007slmg-np-activex-justep | ffactivex/FakeDispatcherWrap.asm | Assembly | mpl11 | 1,879 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <comdef.h>
#include "npactivex.h"
#include "scriptable.h"
#include "common/PropertyList.h"
#include "common/PropertyBag.h"
#include "common/ItemContainer.h"
#include "common/ControlSite.h"
#include "common/ControlSiteIPFrame.h"
#include "common/ControlEventSink.h"
#include "axhost.h"
#include "HTMLDocumentContainer.h"
#ifdef NO_REGISTRY_AUTHORIZE
static const char *WellKnownProgIds[] = {
NULL
};
static const char *WellKnownClsIds[] = {
NULL
};
#endif
static const bool AcceptOnlyWellKnown = false;
static const bool TrustWellKnown = true;
static bool
isWellKnownProgId(const char *progid)
{
#ifdef NO_REGISTRY_AUTHORIZE
unsigned int i = 0;
if (!progid) {
return false;
}
while (WellKnownProgIds[i]) {
if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i])))
return true;
++i;
}
return false;
#else
return true;
#endif
}
static bool
isWellKnownClsId(const char *clsid)
{
#ifdef NO_REGISTRY_AUTHORIZE
unsigned int i = 0;
if (!clsid) {
return false;
}
while (WellKnownClsIds[i]) {
if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i])))
return true;
++i;
}
return false;
#else
return true;
#endif
}
static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result;
CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA);
if (!host) {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
switch (msg)
{
case WM_SETFOCUS:
case WM_KILLFOCUS:
case WM_SIZE:
if (host->Site) {
host->Site->OnDefWindowMessage(msg, wParam, lParam, &result);
return result;
}
else {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
// Window being destroyed
case WM_DESTROY:
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return true;
}
CAxHost::CAxHost(NPP inst):
CHost(inst),
ClsID(CLSID_NULL),
isValidClsID(false),
Sink(NULL),
Site(NULL),
Window(NULL),
OldProc(NULL),
Props_(new PropertyList),
isKnown(false),
CodeBaseUrl(NULL),
noWindow(false)
{
}
CAxHost::~CAxHost()
{
np_log(instance, 0, "AxHost.~AXHost: destroying the control...");
if (Window){
if (OldProc) {
::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc);
OldProc = NULL;
}
::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL);
}
Clear();
delete Props_;
}
void CAxHost::Clear() {
if (Sink) {
Sink->UnsubscribeFromEvents();
Sink->Release();
Sink = NULL;
}
if (Site) {
Site->Detach();
Site->Release();
Site = NULL;
}
if (Props_) {
Props_->Clear();
}
CoFreeUnusedLibraries();
}
CLSID CAxHost::ParseCLSIDFromSetting(LPCSTR str, int length) {
CLSID ret;
CStringW input(str, length);
if (SUCCEEDED(CLSIDFromString(input, &ret)))
return ret;
int pos = input.Find(':');
if (pos != -1) {
CStringW wolestr(_T("{"));
wolestr.Append(input.Mid(pos + 1));
wolestr.Append(_T("}"));
if (SUCCEEDED(CLSIDFromString(wolestr.GetString(), &ret)))
return ret;
}
return CLSID_NULL;
}
void
CAxHost::setWindow(HWND win)
{
if (win != Window) {
if (win) {
// subclass window so we can intercept window messages and
// do our drawing to it
OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc);
// associate window with our CAxHost object so we can access
// it in the window procedure
::SetWindowLong(win, GWL_USERDATA, (LONG)this);
}
else {
if (OldProc)
::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc);
::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL);
}
Window = win;
}
}
void CAxHost::ResetWindow() {
UpdateRect(lastRect);
}
HWND
CAxHost::getWinfow()
{
return Window;
}
void
CAxHost::UpdateRect(RECT rcPos)
{
HRESULT hr = -1;
lastRect = rcPos;
if (Site && Window && !noWindow) {
if (Site->GetParentWindow() == NULL) {
hr = Site->Attach(Window, rcPos, NULL);
if (FAILED(hr)) {
np_log(instance, 0, "AxHost.UpdateRect: failed to attach control");
SIZEL zero = {0, 0};
SetRectSize(&zero);
}
}
if (Site->CheckAndResetNeedUpdateContainerSize()) {
UpdateRectSize(&rcPos);
} else {
Site->SetPosition(rcPos);
}
// Ensure clipping on parent to keep child controls happy
::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN);
}
}
void CAxHost::setNoWindow(bool noWindow) {
this->noWindow = noWindow;
}
void CAxHost::UpdateRectSize(LPRECT origRect) {
if (noWindow) {
return;
}
SIZEL szControl;
if (!Site->IsVisibleAtRuntime()) {
szControl.cx = 0;
szControl.cy = 0;
} else {
if (FAILED(Site->GetControlSize(&szControl))) {
return;
}
}
SIZEL szIn;
szIn.cx = origRect->right - origRect->left;
szIn.cy = origRect->bottom - origRect->top;
if (szControl.cx != szIn.cx || szControl.cy != szIn.cy) {
SetRectSize(&szControl);
}
}
void CAxHost::SetRectSize(LPSIZEL size) {
np_log(instance, 1, "Set object size: x = %d, y = %d", size->cx, size->cy);
NPObjectProxy object;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &object);
static NPIdentifier style = NPNFuncs.getstringidentifier("style");
static NPIdentifier height = NPNFuncs.getstringidentifier("height");
static NPIdentifier width = NPNFuncs.getstringidentifier("width");
NPVariant sHeight, sWidth;
CStringA strHeight, strWidth;
strHeight.Format("%dpx", size->cy);
strWidth.Format("%dpx", size->cx);
STRINGZ_TO_NPVARIANT(strHeight, sHeight);
STRINGZ_TO_NPVARIANT(strWidth, sWidth);
NPVariantProxy styleValue;
NPNFuncs.getproperty(instance, object, style, &styleValue);
NPObject *styleObject = NPVARIANT_TO_OBJECT(styleValue);
NPNFuncs.setproperty(instance, styleObject, height, &sHeight);
NPNFuncs.setproperty(instance, styleObject, width, &sWidth);
}
void CAxHost::SetNPWindow(NPWindow *window) {
RECT rcPos;
setWindow((HWND)window->window);
rcPos.left = 0;
rcPos.top = 0;
rcPos.right = window->width;
rcPos.bottom = window->height;
UpdateRect(rcPos);
}
bool
CAxHost::verifyClsID(LPOLESTR oleClsID)
{
CRegKey keyExplorer;
if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"),
KEY_READ)) {
CRegKey keyCLSID;
if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) {
DWORD dwType = REG_DWORD;
DWORD dwFlags = 0;
DWORD dwBufSize = sizeof(dwFlags);
if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID,
_T("Compatibility Flags"),
NULL,
&dwType,
(LPBYTE)
&dwFlags,
&dwBufSize)) {
// Flags for this reg key
const DWORD kKillBit = 0x00000400;
if (dwFlags & kKillBit) {
np_log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits");
return false;
}
}
}
}
return true;
}
bool
CAxHost::setClsID(const char *clsid)
{
HRESULT hr = -1;
USES_CONVERSION;
LPOLESTR oleClsID = A2OLE(clsid);
if (isWellKnownClsId(clsid)) {
isKnown = true;
}
else if (AcceptOnlyWellKnown) {
np_log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list");
return false;
}
// Check the Internet Explorer list of vulnerable controls
if (oleClsID && verifyClsID(oleClsID)) {
CLSID vclsid;
hr = CLSIDFromString(oleClsID, &vclsid);
if (SUCCEEDED(hr)) {
return setClsID(vclsid);
}
}
np_log(instance, 0, "AxHost.setClsID: failed to set the requested clsid");
return false;
}
bool CAxHost::setClsID(const CLSID& clsid) {
if (clsid != CLSID_NULL) {
this->ClsID = clsid;
isValidClsID = true;
//np_log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid);
return true;
}
return false;
}
void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl)
{
CodeBaseUrl = codeBaseUrl;
}
bool
CAxHost::setClsIDFromProgID(const char *progid)
{
HRESULT hr = -1;
CLSID clsid = CLSID_NULL;
USES_CONVERSION;
LPOLESTR oleClsID = NULL;
LPOLESTR oleProgID = A2OLE(progid);
if (AcceptOnlyWellKnown) {
if (isWellKnownProgId(progid)) {
isKnown = true;
}
else {
np_log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list");
return false;
}
}
hr = CLSIDFromProgID(oleProgID, &clsid);
if (FAILED(hr)) {
np_log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID");
return false;
}
hr = StringFromCLSID(clsid, &oleClsID);
// Check the Internet Explorer list of vulnerable controls
if ( SUCCEEDED(hr)
&& oleClsID
&& verifyClsID(oleClsID)) {
ClsID = clsid;
if (!::IsEqualCLSID(ClsID, CLSID_NULL)) {
isValidClsID = true;
np_log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid);
return true;
}
}
np_log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID");
return false;
}
bool
CAxHost::hasValidClsID()
{
return isValidClsID;
}
static void HTMLContainerDeleter(IUnknown *unk) {
CComAggObject<HTMLDocumentContainer>* val = (CComAggObject<HTMLDocumentContainer>*)(unk);
val->InternalRelease();
}
bool
CAxHost::CreateControl(bool subscribeToEvents)
{
if (!isValidClsID) {
np_log(instance, 0, "AxHost.CreateControl: current location is not trusted");
return false;
}
// Create the control site
CComObject<CControlSite>::CreateInstance(&Site);
if (Site == NULL) {
np_log(instance, 0, "AxHost.CreateControl: CreateInstance failed");
return false;
}
Site->AddRef();
Site->m_bSupportWindowlessActivation = false;
if (TrustWellKnown && isKnown) {
Site->SetSecurityPolicy(NULL);
Site->m_bSafeForScriptingObjectsOnly = false;
}
else {
Site->m_bSafeForScriptingObjectsOnly = true;
}
CComAggObject<HTMLDocumentContainer> *document;
CComAggObject<HTMLDocumentContainer>::CreateInstance(Site->GetUnknown(), &document);
document->m_contained.Init(instance, pHtmlLib);
Site->SetInnerWindow(document, HTMLContainerDeleter);
BSTR url;
document->m_contained.get_LocationURL(&url);
Site->SetUrl(url);
SysFreeString(url);
// Create the object
HRESULT hr;
hr = Site->Create(ClsID, *Props(), CodeBaseUrl);
if (FAILED(hr)) {
np_log(instance, 0, "AxHost.CreateControl: failed to create site for 0x%08x", hr);
return false;
}
#if 0
IUnknown *control = NULL;
Site->GetControlUnknown(&control);
if (!control) {
np_log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)");
return false;
}
// Create the event sink
CComObject<CControlEventSink>::CreateInstance(&Sink);
Sink->AddRef();
Sink->instance = instance;
hr = Sink->SubscribeToEvents(control);
control->Release();
if (FAILED(hr) && subscribeToEvents) {
np_log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed");
// return false;
// It doesn't matter.
}
#endif
np_log(instance, 1, "AxHost.CreateControl: control created successfully");
return true;
}
bool
CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler)
{
HRESULT hr;
DISPID id = 0;
USES_CONVERSION;
LPOLESTR oleName = name;
if (!Sink) {
np_log(instance, 0, "AxHost.AddEventHandler: no valid sink");
return false;
}
hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id);
if (FAILED(hr)) {
np_log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name");
return false;
}
Sink->events[id] = handler;
np_log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name);
return true;
}
int16
CAxHost::HandleEvent(void *event)
{
NPEvent *npEvent = (NPEvent *)event;
LRESULT result = 0;
if (!npEvent) {
return 0;
}
// forward all events to the hosted control
return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result);
}
ScriptBase *
CAxHost::CreateScriptableObject()
{
Scriptable *obj = Scriptable::FromAxHost(instance, this);
if (Site == NULL) {
return obj;
}
static int markedSafe = 0;
if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe == 0)
{
if (MessageBox(NULL, _T("Some objects are not script-safe, would you continue?"), _T("Warining"), MB_YESNO | MB_ICONINFORMATION | MB_ICONASTERISK) == IDYES)
markedSafe = 1;
else
markedSafe = 2;
}
if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe != 1)
{
// Disable scripting.
obj->Invalidate();
}
return obj;
}
HRESULT CAxHost::GetControlUnknown(IUnknown **pObj) {
if (Site == NULL) {
return E_FAIL;
}
return Site->GetControlUnknown(pObj);
}
NPP CAxHost::ResetNPP(NPP npp) {
NPP ret = CHost::ResetNPP(npp);
setWindow(NULL);
Site->Detach();
if (Sink)
Sink->instance = npp;
return ret;
} | 007slmg-np-activex-justep | ffactivex/axhost.cpp | C++ | mpl11 | 15,111 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// npactivex.cpp : Defines the exported functions for the DLL application.
//
#include "npactivex.h"
#include "axhost.h"
#include "atlutil.h"
#include "objectProxy.h"
#include "authorize.h"
#include "common\PropertyList.h"
#include "common\ControlSite.h"
#include "ObjectManager.h"
// A list of trusted domains
// Each domain name may start with a '*' to specify that sub domains are
// trusted as well
// Note that a '.' is not enforced after the '*'
static const char *TrustedLocations[] = {NULL};
static const unsigned int numTrustedLocations = 0;
static const char *LocalhostName = "localhost";
static const bool TrustLocalhost = true;
//
// Gecko API
//
static const char PARAM_ID[] = "id";
static const char PARAM_NAME[] = "name";
static const char PARAM_CLSID[] = "clsid";
static const char PARAM_CLASSID[] = "classid";
static const char PARAM_PROGID[] = "progid";
static const char PARAM_DYNAMIC[] = "dynamic";
static const char PARAM_DEBUG[] = "debugLevel";
static const char PARAM_CODEBASEURL [] = "codeBase";
static const char PARAM_ONEVENT[] = "Event_";
static unsigned int log_level = -1;
// For catch breakpoints.
HRESULT NotImpl() {
return E_NOTIMPL;
}
void log_activex_logging(NPP instance, unsigned int level, const char* filename, int line, char *message, ...) {
if (instance == NULL || level > log_level) {
return;
}
NPObjectProxy globalObj = NULL;
NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log");
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
if (!NPNFuncs.hasmethod(instance, globalObj, commandId)) {
return;
}
int size = 0;
va_list list;
ATL::CStringA str;
ATL::CStringA str2;
va_start(list, message);
str.FormatV(message, list);
str2.Format("0x%08x %s:%d %s", instance, filename, line, str.GetString());
va_end(list);
NPVariant vars[1];
const char* formatted = str2.GetString();
STRINGZ_TO_NPVARIANT(formatted, vars[0]);
NPVariantProxy result1;
NPNFuncs.invoke(instance, globalObj, commandId, vars, 1, &result1);
}
void InstallLogAction(NPP instance) {
NPVariantProxy result1;
NPObjectProxy globalObj = NULL;
NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log");
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
if (NPNFuncs.hasmethod(instance, globalObj, commandId)) {
return;
}
const char* definition = "function __npactivex_log(message)"
"{var controlLogEvent='__npactivex_log_event__';"
"var e=document.createEvent('TextEvent');e.initTextEvent(controlLogEvent,false,false,null,message);window.dispatchEvent(e)}";
NPString def;
def.UTF8Characters = definition;
def.UTF8Length = strlen(definition);
NPNFuncs.evaluate(instance, globalObj, &def, &result1);
}
void
log_internal_console(NPP instance, unsigned int level, char *message, ...)
{
NPVariantProxy result1, result2;
NPVariant args;
NPObjectProxy globalObj = NULL, consoleObj = NULL;
bool rc = false;
char *formatted = NULL;
char *new_formatted = NULL;
int buff_len = 0;
int size = 0;
va_list list;
if (level > log_level) {
return;
}
buff_len = strlen(message);
char *new_message = (char *)malloc(buff_len + 10);
sprintf(new_message, "%%s %%d: %s", message);
buff_len += buff_len / 10;
formatted = (char *)calloc(1, buff_len);
while (true) {
va_start(list, message);
size = vsnprintf_s(formatted, buff_len, _TRUNCATE, new_message, list);
va_end(list);
if (size > -1 && size < buff_len)
break;
buff_len *= 2;
new_formatted = (char *)realloc(formatted, buff_len);
if (NULL == new_formatted) {
free(formatted);
return;
}
formatted = new_formatted;
new_formatted = NULL;
}
free(new_message);
if (instance == NULL) {
free(formatted);
return;
}
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
if (NPNFuncs.getproperty(instance, globalObj, NPNFuncs.getstringidentifier("console"), &result1)) {
consoleObj = NPVARIANT_TO_OBJECT(result1);
NPIdentifier handler = NPNFuncs.getstringidentifier("log");
STRINGZ_TO_NPVARIANT(formatted, args);
bool success = NPNFuncs.invoke(instance, consoleObj, handler, &args, 1, &result2);
}
free(formatted);
}
static bool
MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl)
{
USES_CONVERSION;
BOOL rc = false;
CUrl url;
if (!numTrustedLocations) {
return true;
}
rc = url.CrackUrl(matchUrl, ATL_URL_DECODE);
if (!rc) {
np_log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL");
return false;
}
if ( (url.GetScheme() == ATL_URL_SCHEME_FILE)
|| (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){
return TrustLocalhost;
}
for (unsigned int i = 0; i < numTrustedLocations; ++i) {
if (TrustedLocations[i][0] == '*') {
// sub domains are trusted
unsigned int len = strlen(TrustedLocations[i]);
bool match = 0;
if (url.GetHostNameLength() < len) {
// can't be a match
continue;
}
--len; // skip the '*'
match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name
TrustedLocations[i] + 1, // skip the '*'
len) == 0 ? true : false;
if (match) {
return true;
}
}
else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) {
return true;
}
}
return false;
}
static bool
VerifySiteLock(NPP instance)
{
// This approach is not used.
return true;
#if 0
USES_CONVERSION;
NPObjectProxy globalObj;
NPIdentifier identifier;
NPVariantProxy varLocation;
NPVariantProxy varHref;
bool rc = false;
// Get the window object.
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
// Create a "location" identifier.
identifier = NPNFuncs.getstringidentifier("location");
// Get the location property from the window object (which is another object).
rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation);
if (!rc){
np_log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object");
return false;
}
// Get a pointer to the "location" object.
NPObject *locationObj = varLocation.value.objectValue;
// Create a "href" identifier.
identifier = NPNFuncs.getstringidentifier("href");
// Get the location property from the location object.
rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref);
if (!rc) {
np_log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property");
return false;
}
rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters));
if (false == rc) {
np_log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted");
}
return rc;
#endif
}
static bool FillProperties(CAxHost *host, NPP instance) {
NPObjectProxy embed;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed);
// Traverse through childs
NPVariantProxy var_childNodes;
NPVariantProxy var_length;
NPVariant str_name, str_value;
if (!NPNFuncs.getproperty(instance, embed, NPNFuncs.getstringidentifier("childNodes"), &var_childNodes))
return true;
if (!NPVARIANT_IS_OBJECT(var_childNodes))
return true;
NPObject *childNodes = NPVARIANT_TO_OBJECT(var_childNodes);
VOID_TO_NPVARIANT(var_length);
if (!NPNFuncs.getproperty(instance, childNodes, NPNFuncs.getstringidentifier("length"), &var_length))
return true;
USES_CONVERSION;
int length = 0;
if (NPVARIANT_IS_INT32(var_length))
length = NPVARIANT_TO_INT32(var_length);
if (NPVARIANT_IS_DOUBLE(var_length))
length = static_cast<int>(NPVARIANT_TO_DOUBLE(var_length));
NPIdentifier idname = NPNFuncs.getstringidentifier("nodeName");
NPIdentifier idAttr = NPNFuncs.getstringidentifier("getAttribute");
STRINGZ_TO_NPVARIANT("name", str_name);
STRINGZ_TO_NPVARIANT("value", str_value);
for (int i = 0; i < length; ++i) {
NPIdentifier id = NPNFuncs.getintidentifier(i);
NPVariantProxy var_par;
NPVariantProxy var_nodeName, var_parName, var_parValue;
if (!NPNFuncs.getproperty(instance, childNodes, id, &var_par))
continue;
if (!NPVARIANT_IS_OBJECT(var_par))
continue;
NPObject *param_obj = NPVARIANT_TO_OBJECT(var_par);
if (!NPNFuncs.getproperty(instance, param_obj, idname, &var_nodeName))
continue;
if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "embed", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) == 0) {
NPVariantProxy type;
NPVariant typestr;
STRINGZ_TO_NPVARIANT("type", typestr);
if (!NPNFuncs.invoke(instance, param_obj, idAttr, &typestr, 1, &type))
continue;
if (!NPVARIANT_IS_STRING(type))
continue;
CStringA command, mimetype(NPVARIANT_TO_STRING(type).UTF8Characters, NPVARIANT_TO_STRING(type).UTF8Length);
command.Format("navigator.mimeTypes[\'%s\'] != null", mimetype);
NPString str = {command.GetString(), command.GetLength()};
NPVariantProxy value;
NPObjectProxy window;
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &window);
NPNFuncs.evaluate(instance, window, &str, &value);
if (NPVARIANT_IS_BOOLEAN(value) && NPVARIANT_TO_BOOLEAN(value)) {
// The embed is supported by chrome. Fallback automatically.
np_log(instance, 1, "This control has a valid embed element %s", mimetype.GetString());
return false;
}
}
if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "param", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) != 0)
continue;
if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_name, 1, &var_parName))
continue;
if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_value, 1, &var_parValue))
continue;
if (!NPVARIANT_IS_STRING(var_parName) || !NPVARIANT_IS_STRING(var_parValue))
continue;
CComBSTR paramName(NPVARIANT_TO_STRING(var_parName).UTF8Length, NPVARIANT_TO_STRING(var_parName).UTF8Characters);
CComBSTR paramValue(NPVARIANT_TO_STRING(var_parValue).UTF8Length, NPVARIANT_TO_STRING(var_parValue).UTF8Characters);
// Add named parameter to list
CComVariant v(paramValue);
host->Props()->AddOrReplaceNamedProperty(paramName, v);
}
return true;
}
NPError CreateControl(NPP instance, int16 argc, char *argn[], char *argv[], CAxHost **phost) {
// Create a plugin instance, the actual control will be created once we
// are given a window handle
USES_CONVERSION;
PropertyList events;
CAxHost *host = new CAxHost(instance);
*phost = host;
if (!host) {
np_log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host");
return NPERR_OUT_OF_MEMORY_ERROR;
}
// Iterate over the arguments we've been passed
for (int i = 0; i < argc; ++i) {
// search for any needed information: clsid, event handling directives, etc.
if (strnicmp(argn[i], PARAM_CLASSID, sizeof(PARAM_CLASSID)) == 0) {
char clsid[100];
strncpy(clsid, argv[i], 80);
strcat(clsid, "}");
char* id = strchr(clsid, ':');
if (id == NULL)
continue;
*id = '{';
host->setClsID(id);
}
else if (0 == strnicmp(argn[i], PARAM_NAME, sizeof(PARAM_NAME)) ||
0 == strnicmp(argn[i], PARAM_ID, sizeof(PARAM_ID))) {
np_log(instance, 1, "instance %s: %s", argn[i], argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_CLSID, sizeof(PARAM_CLSID))) {
// The class id of the control we are asked to load
host->setClsID(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_PROGID, sizeof(PARAM_PROGID))) {
// The class id of the control we are asked to load
host->setClsIDFromProgID(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_DEBUG, sizeof(PARAM_DEBUG))) {
// Logging verbosity
log_level = atoi(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_ONEVENT, sizeof(PARAM_ONEVENT))) {
// A request to handle one of the activex's events in JS
events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i])));
}
else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, sizeof(PARAM_CODEBASEURL))) {
if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) {
host->setCodeBaseUrl(A2W(argv[i]));
}
else {
np_log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location");
}
}
else if (0 == strnicmp(argn[i], PARAM_DYNAMIC, sizeof(PARAM_DYNAMIC))) {
host->setNoWindow(true);
}
}
if (!FillProperties(host, instance)) {
return NPERR_GENERIC_ERROR;
}
// Make sure we have all the information we need to initialize a new instance
if (!host->hasValidClsID()) {
np_log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID");
// create later.
return NPERR_NO_ERROR;
}
instance->pdata = host;
// if no events were requested, don't fail if subscribing fails
if (!host->CreateControl(events.GetSize() ? true : false)) {
np_log(instance, 0, "AxHost.NPP_New: failed to create the control");
return NPERR_GENERIC_ERROR;
}
for (unsigned int j = 0; j < events.GetSize(); j++) {
if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) {
//rc = NPERR_GENERIC_ERROR;
//break;
}
}
np_log(instance, 1, "%08x AxHost.NPP_New: Create control finished", instance);
return NPERR_NO_ERROR;
}
/*
* Create a new plugin instance, most probably through an embed/object HTML
* element.
*
* Any private data we want to keep for this instance can be saved into
* [instance->pdata].
* [saved] might hold information a previous instance that was invoked from the
* same URL has saved for us.
*/
NPError
NPP_New(NPMIMEType pluginType,
NPP instance, uint16 mode,
int16 argc, char *argn[],
char *argv[], NPSavedData *saved)
{
NPError rc = NPERR_NO_ERROR;
NPObject *browser = NULL;
int16 i = 0;
if (!instance || (0 == NPNFuncs.size)) {
return NPERR_INVALID_PARAM;
}
instance->pdata = NULL;
#ifdef NO_REGISTRY_AUTHORIZE
// Verify that we're running from a trusted location
if (!VerifySiteLock(instance)) {
return NPERR_GENERIC_ERROR;
}
#else
if (!TestAuthorization (instance,
argc,
argn,
argv,
pluginType)) {
return NPERR_GENERIC_ERROR;
}
#endif
InstallLogAction(instance);
if (stricmp(pluginType, "application/x-itst-activex") == 0) {
CAxHost *host = NULL;
/*
ObjectManager* manager = ObjectManager::GetManager(instance);
if (manager && !(host = dynamic_cast<CAxHost*>(manager->GetPreviousObject(instance)))) {
// Object is created before
manager->RequestObjectOwnership(instance, host);
} else
*/
{
rc = CreateControl(instance, argc, argn, argv, &host);
if (NPERR_NO_ERROR != rc) {
delete host;
instance->pdata = NULL;
host = NULL;
return rc;
}
}
if (host) {
host->RegisterObject();
instance->pdata = host;
}
} else if (stricmp(pluginType, "application/activex-manager") == 0) {
// disabled now!!
return rc = NPERR_GENERIC_ERROR;
ObjectManager *manager = new ObjectManager(instance);
manager->RegisterObject();
instance->pdata = manager;
}
return rc;
}
/*
* Destroy an existing plugin instance.
*
* [save] can be used to save information for a future instance of our plugin
* that'll be invoked by the same URL.
*/
NPError
NPP_Destroy(NPP instance, NPSavedData **save)
{
if (!instance) {
return NPERR_INVALID_PARAM;
}
CHost *host = (CHost *)instance->pdata;
if (host) {
np_log(instance, 0, "NPP_Destroy: destroying the control...");
//host->UnRegisterObject();
host->Release();
instance->pdata = NULL;
/*
ObjectManager *manager = ObjectManager::GetManager(instance);
CAxHost *axHost = dynamic_cast<CAxHost*>(host);
if (manager && axHost) {
manager->RetainOwnership(axHost);
} else {
np_log(instance, 0, "NPP_Destroy: destroying the control...");
host->Release();
instance->pdata = NULL;
}*/
}
return NPERR_NO_ERROR;
}
/*
* Sets an instance's window parameters.
*/
NPError
NPP_SetWindow(NPP instance, NPWindow *window)
{
CAxHost *host = NULL;
if (!instance || !instance->pdata) {
return NPERR_INVALID_PARAM;
}
host = dynamic_cast<CAxHost*>((CHost *)instance->pdata);
if (host) {
host->SetNPWindow(window);
}
return NPERR_NO_ERROR;
}
| 007slmg-np-activex-justep | ffactivex/npactivex.cpp | C++ | mpl11 | 18,456 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "ObjectManager.h"
#include "npactivex.h"
#include "host.h"
#include "axhost.h"
#include "objectProxy.h"
#include "scriptable.h"
#define MANAGER_OBJECT_ID "__activex_manager_IIID_"
NPClass ObjectManager::npClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ ObjectManager::_Allocate,
/* deallocate */ ObjectManager::Deallocate,
/* invalidate */ NULL,
/* hasMethod */ ObjectManager::HasMethod,
/* invoke */ ObjectManager::Invoke,
/* invokeDefault */ NULL,
/* hasProperty */ ObjectManager::HasProperty,
/* getProperty */ ObjectManager::GetProperty,
/* setProperty */ ObjectManager::SetProperty,
/* removeProperty */ NULL,
/* enumerate */ NULL,
/* construct */ NULL
};
ObjectManager::ObjectManager(NPP npp_) : CHost(npp_) {
}
ObjectManager::~ObjectManager(void)
{
for (uint i = 0; i < hosts.size(); ++i) {
hosts[i]->Release();
}
for (uint i = 0; i < dynamic_hosts.size(); ++i) {
dynamic_hosts[i]->Release();
}
}
ObjectManager* ObjectManager::GetManager(NPP npp) {
NPObjectProxy window;
NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window);
NPVariantProxy document, obj;
NPVariant par;
STRINGZ_TO_NPVARIANT(MANAGER_OBJECT_ID, par);
if (!NPNFuncs.getproperty(npp, window, NPNFuncs.getstringidentifier("document"), &document))
return NULL;
if (!NPNFuncs.invoke(npp, document.value.objectValue, NPNFuncs.getstringidentifier("getElementById"), &par, 1, &obj))
return NULL;
if (NPVARIANT_IS_OBJECT(obj)) {
NPObject *manager = NPVARIANT_TO_OBJECT(obj);
CHost *host = GetInternalObject(npp, manager);
if (host)
return dynamic_cast<ObjectManager*>(host);
}
return NULL;
}
CHost* ObjectManager::GetPreviousObject(NPP npp) {
NPObjectProxy embed;
NPNFuncs.getvalue(npp, NPNVPluginElementNPObject, &embed);
return GetMyScriptObject()->host;
}
bool ObjectManager::HasMethod(NPObject *npobj, NPIdentifier name) {
return name == NPNFuncs.getstringidentifier("CreateControlByProgId");
}
bool ObjectManager::Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
ScriptManager *obj = static_cast<ScriptManager*>(npobj);
if (name == NPNFuncs.getstringidentifier("CreateControlByProgId")) {
if (argCount != 1 || !NPVARIANT_IS_STRING(args[0])) {
NPNFuncs.setexception(npobj, "Invalid arguments");
return false;
}
CAxHost* host = new CAxHost(obj->instance);
CStringA str(NPVARIANT_TO_STRING(args[0]).UTF8Characters, NPVARIANT_TO_STRING(args[0]).UTF8Length);
host->setClsIDFromProgID(str.GetString());
if (!host->CreateControl(false)) {
NPNFuncs.setexception(npobj, "Error creating object");
return false;
}
ObjectManager *manager = static_cast<ObjectManager*>(obj->host);
manager->dynamic_hosts.push_back(host);
OBJECT_TO_NPVARIANT(host->CreateScriptableObject(), *result);
return true;
}
return false;
}
bool ObjectManager::HasProperty(NPObject *npObj, NPIdentifier name) {
if (name == NPNFuncs.getstringidentifier("internalId"))
return true;
if (name == NPNFuncs.getstringidentifier("isValid"))
return true;
return false;
}
bool ObjectManager::GetProperty(NPObject *npObj, NPIdentifier name, NPVariant *value) {
if (name == NPNFuncs.getstringidentifier("internalId")) {
int len = strlen(MANAGER_OBJECT_ID);
char *stra = (char*)NPNFuncs.memalloc(len + 1);
strcpy(stra, MANAGER_OBJECT_ID);
STRINGN_TO_NPVARIANT(stra, len, *value);
return true;
}
if (name == NPNFuncs.getstringidentifier("isValid")) {
BOOLEAN_TO_NPVARIANT(TRUE, *value);
return true;
}
return false;
}
bool ObjectManager::SetProperty(NPObject *npObj, NPIdentifier name, const NPVariant *value) {
return false;
}
bool ObjectManager::RequestObjectOwnership(NPP newNpp, CAxHost* host) {
// reference count of host not changed.
for (uint i = 0; i < hosts.size(); ++i) {
if (hosts[i] == host) {
hosts[i] = hosts.back();
hosts.pop_back();
host->ResetNPP(newNpp);
newNpp->pdata = host;
return true;
}
}
return false;
}
void ObjectManager::RetainOwnership(CAxHost* host) {
hosts.push_back(host);
host->ResetNPP(instance);
}
ScriptBase* ObjectManager::CreateScriptableObject() {
ScriptBase* obj = static_cast<ScriptBase*>(NPNFuncs.createobject(instance, &npClass));
return obj;
}
void ObjectManager::Deallocate(NPObject *obj) {
delete static_cast<ScriptManager*>(obj);
} | 007slmg-np-activex-justep | ffactivex/ObjectManager.cpp | C++ | mpl11 | 5,998 |
; Copyright qiuc12@gmail.com
; This file is generated automatically by python. DON'T MODIFY IT!
.386
.model flat
_DualProcessCommandWrap proto
PUBLIC ?fv0@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv1@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv2@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv3@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv4@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv5@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv6@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv7@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv8@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv9@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv10@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv11@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv12@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv13@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv14@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv15@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv16@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv17@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv18@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv19@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv20@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv21@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv22@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv23@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv24@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv25@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv26@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv27@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv28@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv29@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv30@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv31@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv32@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv33@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv34@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv35@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv36@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv37@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv38@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv39@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv40@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv41@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv42@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv43@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv44@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv45@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv46@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv47@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv48@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv49@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv50@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv51@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv52@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv53@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv54@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv55@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv56@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv57@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv58@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv59@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv60@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv61@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv62@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv63@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv64@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv65@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv66@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv67@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv68@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv69@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv70@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv71@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv72@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv73@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv74@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv75@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv76@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv77@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv78@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv79@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv80@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv81@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv82@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv83@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv84@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv85@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv86@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv87@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv88@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv89@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv90@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv91@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv92@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv93@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv94@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv95@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv96@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv97@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv98@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv99@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv100@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv101@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv102@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv103@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv104@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv105@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv106@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv107@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv108@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv109@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv110@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv111@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv112@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv113@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv114@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv115@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv116@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv117@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv118@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv119@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv120@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv121@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv122@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv123@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv124@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv125@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv126@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv127@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv128@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv129@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv130@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv131@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv132@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv133@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv134@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv135@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv136@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv137@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv138@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv139@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv140@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv141@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv142@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv143@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv144@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv145@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv146@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv147@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv148@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv149@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv150@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv151@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv152@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv153@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv154@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv155@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv156@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv157@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv158@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv159@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv160@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv161@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv162@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv163@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv164@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv165@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv166@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv167@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv168@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv169@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv170@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv171@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv172@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv173@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv174@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv175@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv176@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv177@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv178@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv179@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv180@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv181@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv182@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv183@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv184@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv185@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv186@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv187@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv188@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv189@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv190@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv191@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv192@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv193@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv194@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv195@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv196@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv197@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv198@FakeDispatcherBase@@EAGJXZ
PUBLIC ?fv199@FakeDispatcherBase@@EAGJXZ
.code
?fv0@FakeDispatcherBase@@EAGJXZ proc
push 0
jmp _DualProcessCommandWrap
?fv0@FakeDispatcherBase@@EAGJXZ endp
?fv1@FakeDispatcherBase@@EAGJXZ proc
push 1
jmp _DualProcessCommandWrap
?fv1@FakeDispatcherBase@@EAGJXZ endp
?fv2@FakeDispatcherBase@@EAGJXZ proc
push 2
jmp _DualProcessCommandWrap
?fv2@FakeDispatcherBase@@EAGJXZ endp
?fv3@FakeDispatcherBase@@EAGJXZ proc
push 3
jmp _DualProcessCommandWrap
?fv3@FakeDispatcherBase@@EAGJXZ endp
?fv4@FakeDispatcherBase@@EAGJXZ proc
push 4
jmp _DualProcessCommandWrap
?fv4@FakeDispatcherBase@@EAGJXZ endp
?fv5@FakeDispatcherBase@@EAGJXZ proc
push 5
jmp _DualProcessCommandWrap
?fv5@FakeDispatcherBase@@EAGJXZ endp
?fv6@FakeDispatcherBase@@EAGJXZ proc
push 6
jmp _DualProcessCommandWrap
?fv6@FakeDispatcherBase@@EAGJXZ endp
?fv7@FakeDispatcherBase@@EAGJXZ proc
push 7
jmp _DualProcessCommandWrap
?fv7@FakeDispatcherBase@@EAGJXZ endp
?fv8@FakeDispatcherBase@@EAGJXZ proc
push 8
jmp _DualProcessCommandWrap
?fv8@FakeDispatcherBase@@EAGJXZ endp
?fv9@FakeDispatcherBase@@EAGJXZ proc
push 9
jmp _DualProcessCommandWrap
?fv9@FakeDispatcherBase@@EAGJXZ endp
?fv10@FakeDispatcherBase@@EAGJXZ proc
push 10
jmp _DualProcessCommandWrap
?fv10@FakeDispatcherBase@@EAGJXZ endp
?fv11@FakeDispatcherBase@@EAGJXZ proc
push 11
jmp _DualProcessCommandWrap
?fv11@FakeDispatcherBase@@EAGJXZ endp
?fv12@FakeDispatcherBase@@EAGJXZ proc
push 12
jmp _DualProcessCommandWrap
?fv12@FakeDispatcherBase@@EAGJXZ endp
?fv13@FakeDispatcherBase@@EAGJXZ proc
push 13
jmp _DualProcessCommandWrap
?fv13@FakeDispatcherBase@@EAGJXZ endp
?fv14@FakeDispatcherBase@@EAGJXZ proc
push 14
jmp _DualProcessCommandWrap
?fv14@FakeDispatcherBase@@EAGJXZ endp
?fv15@FakeDispatcherBase@@EAGJXZ proc
push 15
jmp _DualProcessCommandWrap
?fv15@FakeDispatcherBase@@EAGJXZ endp
?fv16@FakeDispatcherBase@@EAGJXZ proc
push 16
jmp _DualProcessCommandWrap
?fv16@FakeDispatcherBase@@EAGJXZ endp
?fv17@FakeDispatcherBase@@EAGJXZ proc
push 17
jmp _DualProcessCommandWrap
?fv17@FakeDispatcherBase@@EAGJXZ endp
?fv18@FakeDispatcherBase@@EAGJXZ proc
push 18
jmp _DualProcessCommandWrap
?fv18@FakeDispatcherBase@@EAGJXZ endp
?fv19@FakeDispatcherBase@@EAGJXZ proc
push 19
jmp _DualProcessCommandWrap
?fv19@FakeDispatcherBase@@EAGJXZ endp
?fv20@FakeDispatcherBase@@EAGJXZ proc
push 20
jmp _DualProcessCommandWrap
?fv20@FakeDispatcherBase@@EAGJXZ endp
?fv21@FakeDispatcherBase@@EAGJXZ proc
push 21
jmp _DualProcessCommandWrap
?fv21@FakeDispatcherBase@@EAGJXZ endp
?fv22@FakeDispatcherBase@@EAGJXZ proc
push 22
jmp _DualProcessCommandWrap
?fv22@FakeDispatcherBase@@EAGJXZ endp
?fv23@FakeDispatcherBase@@EAGJXZ proc
push 23
jmp _DualProcessCommandWrap
?fv23@FakeDispatcherBase@@EAGJXZ endp
?fv24@FakeDispatcherBase@@EAGJXZ proc
push 24
jmp _DualProcessCommandWrap
?fv24@FakeDispatcherBase@@EAGJXZ endp
?fv25@FakeDispatcherBase@@EAGJXZ proc
push 25
jmp _DualProcessCommandWrap
?fv25@FakeDispatcherBase@@EAGJXZ endp
?fv26@FakeDispatcherBase@@EAGJXZ proc
push 26
jmp _DualProcessCommandWrap
?fv26@FakeDispatcherBase@@EAGJXZ endp
?fv27@FakeDispatcherBase@@EAGJXZ proc
push 27
jmp _DualProcessCommandWrap
?fv27@FakeDispatcherBase@@EAGJXZ endp
?fv28@FakeDispatcherBase@@EAGJXZ proc
push 28
jmp _DualProcessCommandWrap
?fv28@FakeDispatcherBase@@EAGJXZ endp
?fv29@FakeDispatcherBase@@EAGJXZ proc
push 29
jmp _DualProcessCommandWrap
?fv29@FakeDispatcherBase@@EAGJXZ endp
?fv30@FakeDispatcherBase@@EAGJXZ proc
push 30
jmp _DualProcessCommandWrap
?fv30@FakeDispatcherBase@@EAGJXZ endp
?fv31@FakeDispatcherBase@@EAGJXZ proc
push 31
jmp _DualProcessCommandWrap
?fv31@FakeDispatcherBase@@EAGJXZ endp
?fv32@FakeDispatcherBase@@EAGJXZ proc
push 32
jmp _DualProcessCommandWrap
?fv32@FakeDispatcherBase@@EAGJXZ endp
?fv33@FakeDispatcherBase@@EAGJXZ proc
push 33
jmp _DualProcessCommandWrap
?fv33@FakeDispatcherBase@@EAGJXZ endp
?fv34@FakeDispatcherBase@@EAGJXZ proc
push 34
jmp _DualProcessCommandWrap
?fv34@FakeDispatcherBase@@EAGJXZ endp
?fv35@FakeDispatcherBase@@EAGJXZ proc
push 35
jmp _DualProcessCommandWrap
?fv35@FakeDispatcherBase@@EAGJXZ endp
?fv36@FakeDispatcherBase@@EAGJXZ proc
push 36
jmp _DualProcessCommandWrap
?fv36@FakeDispatcherBase@@EAGJXZ endp
?fv37@FakeDispatcherBase@@EAGJXZ proc
push 37
jmp _DualProcessCommandWrap
?fv37@FakeDispatcherBase@@EAGJXZ endp
?fv38@FakeDispatcherBase@@EAGJXZ proc
push 38
jmp _DualProcessCommandWrap
?fv38@FakeDispatcherBase@@EAGJXZ endp
?fv39@FakeDispatcherBase@@EAGJXZ proc
push 39
jmp _DualProcessCommandWrap
?fv39@FakeDispatcherBase@@EAGJXZ endp
?fv40@FakeDispatcherBase@@EAGJXZ proc
push 40
jmp _DualProcessCommandWrap
?fv40@FakeDispatcherBase@@EAGJXZ endp
?fv41@FakeDispatcherBase@@EAGJXZ proc
push 41
jmp _DualProcessCommandWrap
?fv41@FakeDispatcherBase@@EAGJXZ endp
?fv42@FakeDispatcherBase@@EAGJXZ proc
push 42
jmp _DualProcessCommandWrap
?fv42@FakeDispatcherBase@@EAGJXZ endp
?fv43@FakeDispatcherBase@@EAGJXZ proc
push 43
jmp _DualProcessCommandWrap
?fv43@FakeDispatcherBase@@EAGJXZ endp
?fv44@FakeDispatcherBase@@EAGJXZ proc
push 44
jmp _DualProcessCommandWrap
?fv44@FakeDispatcherBase@@EAGJXZ endp
?fv45@FakeDispatcherBase@@EAGJXZ proc
push 45
jmp _DualProcessCommandWrap
?fv45@FakeDispatcherBase@@EAGJXZ endp
?fv46@FakeDispatcherBase@@EAGJXZ proc
push 46
jmp _DualProcessCommandWrap
?fv46@FakeDispatcherBase@@EAGJXZ endp
?fv47@FakeDispatcherBase@@EAGJXZ proc
push 47
jmp _DualProcessCommandWrap
?fv47@FakeDispatcherBase@@EAGJXZ endp
?fv48@FakeDispatcherBase@@EAGJXZ proc
push 48
jmp _DualProcessCommandWrap
?fv48@FakeDispatcherBase@@EAGJXZ endp
?fv49@FakeDispatcherBase@@EAGJXZ proc
push 49
jmp _DualProcessCommandWrap
?fv49@FakeDispatcherBase@@EAGJXZ endp
?fv50@FakeDispatcherBase@@EAGJXZ proc
push 50
jmp _DualProcessCommandWrap
?fv50@FakeDispatcherBase@@EAGJXZ endp
?fv51@FakeDispatcherBase@@EAGJXZ proc
push 51
jmp _DualProcessCommandWrap
?fv51@FakeDispatcherBase@@EAGJXZ endp
?fv52@FakeDispatcherBase@@EAGJXZ proc
push 52
jmp _DualProcessCommandWrap
?fv52@FakeDispatcherBase@@EAGJXZ endp
?fv53@FakeDispatcherBase@@EAGJXZ proc
push 53
jmp _DualProcessCommandWrap
?fv53@FakeDispatcherBase@@EAGJXZ endp
?fv54@FakeDispatcherBase@@EAGJXZ proc
push 54
jmp _DualProcessCommandWrap
?fv54@FakeDispatcherBase@@EAGJXZ endp
?fv55@FakeDispatcherBase@@EAGJXZ proc
push 55
jmp _DualProcessCommandWrap
?fv55@FakeDispatcherBase@@EAGJXZ endp
?fv56@FakeDispatcherBase@@EAGJXZ proc
push 56
jmp _DualProcessCommandWrap
?fv56@FakeDispatcherBase@@EAGJXZ endp
?fv57@FakeDispatcherBase@@EAGJXZ proc
push 57
jmp _DualProcessCommandWrap
?fv57@FakeDispatcherBase@@EAGJXZ endp
?fv58@FakeDispatcherBase@@EAGJXZ proc
push 58
jmp _DualProcessCommandWrap
?fv58@FakeDispatcherBase@@EAGJXZ endp
?fv59@FakeDispatcherBase@@EAGJXZ proc
push 59
jmp _DualProcessCommandWrap
?fv59@FakeDispatcherBase@@EAGJXZ endp
?fv60@FakeDispatcherBase@@EAGJXZ proc
push 60
jmp _DualProcessCommandWrap
?fv60@FakeDispatcherBase@@EAGJXZ endp
?fv61@FakeDispatcherBase@@EAGJXZ proc
push 61
jmp _DualProcessCommandWrap
?fv61@FakeDispatcherBase@@EAGJXZ endp
?fv62@FakeDispatcherBase@@EAGJXZ proc
push 62
jmp _DualProcessCommandWrap
?fv62@FakeDispatcherBase@@EAGJXZ endp
?fv63@FakeDispatcherBase@@EAGJXZ proc
push 63
jmp _DualProcessCommandWrap
?fv63@FakeDispatcherBase@@EAGJXZ endp
?fv64@FakeDispatcherBase@@EAGJXZ proc
push 64
jmp _DualProcessCommandWrap
?fv64@FakeDispatcherBase@@EAGJXZ endp
?fv65@FakeDispatcherBase@@EAGJXZ proc
push 65
jmp _DualProcessCommandWrap
?fv65@FakeDispatcherBase@@EAGJXZ endp
?fv66@FakeDispatcherBase@@EAGJXZ proc
push 66
jmp _DualProcessCommandWrap
?fv66@FakeDispatcherBase@@EAGJXZ endp
?fv67@FakeDispatcherBase@@EAGJXZ proc
push 67
jmp _DualProcessCommandWrap
?fv67@FakeDispatcherBase@@EAGJXZ endp
?fv68@FakeDispatcherBase@@EAGJXZ proc
push 68
jmp _DualProcessCommandWrap
?fv68@FakeDispatcherBase@@EAGJXZ endp
?fv69@FakeDispatcherBase@@EAGJXZ proc
push 69
jmp _DualProcessCommandWrap
?fv69@FakeDispatcherBase@@EAGJXZ endp
?fv70@FakeDispatcherBase@@EAGJXZ proc
push 70
jmp _DualProcessCommandWrap
?fv70@FakeDispatcherBase@@EAGJXZ endp
?fv71@FakeDispatcherBase@@EAGJXZ proc
push 71
jmp _DualProcessCommandWrap
?fv71@FakeDispatcherBase@@EAGJXZ endp
?fv72@FakeDispatcherBase@@EAGJXZ proc
push 72
jmp _DualProcessCommandWrap
?fv72@FakeDispatcherBase@@EAGJXZ endp
?fv73@FakeDispatcherBase@@EAGJXZ proc
push 73
jmp _DualProcessCommandWrap
?fv73@FakeDispatcherBase@@EAGJXZ endp
?fv74@FakeDispatcherBase@@EAGJXZ proc
push 74
jmp _DualProcessCommandWrap
?fv74@FakeDispatcherBase@@EAGJXZ endp
?fv75@FakeDispatcherBase@@EAGJXZ proc
push 75
jmp _DualProcessCommandWrap
?fv75@FakeDispatcherBase@@EAGJXZ endp
?fv76@FakeDispatcherBase@@EAGJXZ proc
push 76
jmp _DualProcessCommandWrap
?fv76@FakeDispatcherBase@@EAGJXZ endp
?fv77@FakeDispatcherBase@@EAGJXZ proc
push 77
jmp _DualProcessCommandWrap
?fv77@FakeDispatcherBase@@EAGJXZ endp
?fv78@FakeDispatcherBase@@EAGJXZ proc
push 78
jmp _DualProcessCommandWrap
?fv78@FakeDispatcherBase@@EAGJXZ endp
?fv79@FakeDispatcherBase@@EAGJXZ proc
push 79
jmp _DualProcessCommandWrap
?fv79@FakeDispatcherBase@@EAGJXZ endp
?fv80@FakeDispatcherBase@@EAGJXZ proc
push 80
jmp _DualProcessCommandWrap
?fv80@FakeDispatcherBase@@EAGJXZ endp
?fv81@FakeDispatcherBase@@EAGJXZ proc
push 81
jmp _DualProcessCommandWrap
?fv81@FakeDispatcherBase@@EAGJXZ endp
?fv82@FakeDispatcherBase@@EAGJXZ proc
push 82
jmp _DualProcessCommandWrap
?fv82@FakeDispatcherBase@@EAGJXZ endp
?fv83@FakeDispatcherBase@@EAGJXZ proc
push 83
jmp _DualProcessCommandWrap
?fv83@FakeDispatcherBase@@EAGJXZ endp
?fv84@FakeDispatcherBase@@EAGJXZ proc
push 84
jmp _DualProcessCommandWrap
?fv84@FakeDispatcherBase@@EAGJXZ endp
?fv85@FakeDispatcherBase@@EAGJXZ proc
push 85
jmp _DualProcessCommandWrap
?fv85@FakeDispatcherBase@@EAGJXZ endp
?fv86@FakeDispatcherBase@@EAGJXZ proc
push 86
jmp _DualProcessCommandWrap
?fv86@FakeDispatcherBase@@EAGJXZ endp
?fv87@FakeDispatcherBase@@EAGJXZ proc
push 87
jmp _DualProcessCommandWrap
?fv87@FakeDispatcherBase@@EAGJXZ endp
?fv88@FakeDispatcherBase@@EAGJXZ proc
push 88
jmp _DualProcessCommandWrap
?fv88@FakeDispatcherBase@@EAGJXZ endp
?fv89@FakeDispatcherBase@@EAGJXZ proc
push 89
jmp _DualProcessCommandWrap
?fv89@FakeDispatcherBase@@EAGJXZ endp
?fv90@FakeDispatcherBase@@EAGJXZ proc
push 90
jmp _DualProcessCommandWrap
?fv90@FakeDispatcherBase@@EAGJXZ endp
?fv91@FakeDispatcherBase@@EAGJXZ proc
push 91
jmp _DualProcessCommandWrap
?fv91@FakeDispatcherBase@@EAGJXZ endp
?fv92@FakeDispatcherBase@@EAGJXZ proc
push 92
jmp _DualProcessCommandWrap
?fv92@FakeDispatcherBase@@EAGJXZ endp
?fv93@FakeDispatcherBase@@EAGJXZ proc
push 93
jmp _DualProcessCommandWrap
?fv93@FakeDispatcherBase@@EAGJXZ endp
?fv94@FakeDispatcherBase@@EAGJXZ proc
push 94
jmp _DualProcessCommandWrap
?fv94@FakeDispatcherBase@@EAGJXZ endp
?fv95@FakeDispatcherBase@@EAGJXZ proc
push 95
jmp _DualProcessCommandWrap
?fv95@FakeDispatcherBase@@EAGJXZ endp
?fv96@FakeDispatcherBase@@EAGJXZ proc
push 96
jmp _DualProcessCommandWrap
?fv96@FakeDispatcherBase@@EAGJXZ endp
?fv97@FakeDispatcherBase@@EAGJXZ proc
push 97
jmp _DualProcessCommandWrap
?fv97@FakeDispatcherBase@@EAGJXZ endp
?fv98@FakeDispatcherBase@@EAGJXZ proc
push 98
jmp _DualProcessCommandWrap
?fv98@FakeDispatcherBase@@EAGJXZ endp
?fv99@FakeDispatcherBase@@EAGJXZ proc
push 99
jmp _DualProcessCommandWrap
?fv99@FakeDispatcherBase@@EAGJXZ endp
?fv100@FakeDispatcherBase@@EAGJXZ proc
push 100
jmp _DualProcessCommandWrap
?fv100@FakeDispatcherBase@@EAGJXZ endp
?fv101@FakeDispatcherBase@@EAGJXZ proc
push 101
jmp _DualProcessCommandWrap
?fv101@FakeDispatcherBase@@EAGJXZ endp
?fv102@FakeDispatcherBase@@EAGJXZ proc
push 102
jmp _DualProcessCommandWrap
?fv102@FakeDispatcherBase@@EAGJXZ endp
?fv103@FakeDispatcherBase@@EAGJXZ proc
push 103
jmp _DualProcessCommandWrap
?fv103@FakeDispatcherBase@@EAGJXZ endp
?fv104@FakeDispatcherBase@@EAGJXZ proc
push 104
jmp _DualProcessCommandWrap
?fv104@FakeDispatcherBase@@EAGJXZ endp
?fv105@FakeDispatcherBase@@EAGJXZ proc
push 105
jmp _DualProcessCommandWrap
?fv105@FakeDispatcherBase@@EAGJXZ endp
?fv106@FakeDispatcherBase@@EAGJXZ proc
push 106
jmp _DualProcessCommandWrap
?fv106@FakeDispatcherBase@@EAGJXZ endp
?fv107@FakeDispatcherBase@@EAGJXZ proc
push 107
jmp _DualProcessCommandWrap
?fv107@FakeDispatcherBase@@EAGJXZ endp
?fv108@FakeDispatcherBase@@EAGJXZ proc
push 108
jmp _DualProcessCommandWrap
?fv108@FakeDispatcherBase@@EAGJXZ endp
?fv109@FakeDispatcherBase@@EAGJXZ proc
push 109
jmp _DualProcessCommandWrap
?fv109@FakeDispatcherBase@@EAGJXZ endp
?fv110@FakeDispatcherBase@@EAGJXZ proc
push 110
jmp _DualProcessCommandWrap
?fv110@FakeDispatcherBase@@EAGJXZ endp
?fv111@FakeDispatcherBase@@EAGJXZ proc
push 111
jmp _DualProcessCommandWrap
?fv111@FakeDispatcherBase@@EAGJXZ endp
?fv112@FakeDispatcherBase@@EAGJXZ proc
push 112
jmp _DualProcessCommandWrap
?fv112@FakeDispatcherBase@@EAGJXZ endp
?fv113@FakeDispatcherBase@@EAGJXZ proc
push 113
jmp _DualProcessCommandWrap
?fv113@FakeDispatcherBase@@EAGJXZ endp
?fv114@FakeDispatcherBase@@EAGJXZ proc
push 114
jmp _DualProcessCommandWrap
?fv114@FakeDispatcherBase@@EAGJXZ endp
?fv115@FakeDispatcherBase@@EAGJXZ proc
push 115
jmp _DualProcessCommandWrap
?fv115@FakeDispatcherBase@@EAGJXZ endp
?fv116@FakeDispatcherBase@@EAGJXZ proc
push 116
jmp _DualProcessCommandWrap
?fv116@FakeDispatcherBase@@EAGJXZ endp
?fv117@FakeDispatcherBase@@EAGJXZ proc
push 117
jmp _DualProcessCommandWrap
?fv117@FakeDispatcherBase@@EAGJXZ endp
?fv118@FakeDispatcherBase@@EAGJXZ proc
push 118
jmp _DualProcessCommandWrap
?fv118@FakeDispatcherBase@@EAGJXZ endp
?fv119@FakeDispatcherBase@@EAGJXZ proc
push 119
jmp _DualProcessCommandWrap
?fv119@FakeDispatcherBase@@EAGJXZ endp
?fv120@FakeDispatcherBase@@EAGJXZ proc
push 120
jmp _DualProcessCommandWrap
?fv120@FakeDispatcherBase@@EAGJXZ endp
?fv121@FakeDispatcherBase@@EAGJXZ proc
push 121
jmp _DualProcessCommandWrap
?fv121@FakeDispatcherBase@@EAGJXZ endp
?fv122@FakeDispatcherBase@@EAGJXZ proc
push 122
jmp _DualProcessCommandWrap
?fv122@FakeDispatcherBase@@EAGJXZ endp
?fv123@FakeDispatcherBase@@EAGJXZ proc
push 123
jmp _DualProcessCommandWrap
?fv123@FakeDispatcherBase@@EAGJXZ endp
?fv124@FakeDispatcherBase@@EAGJXZ proc
push 124
jmp _DualProcessCommandWrap
?fv124@FakeDispatcherBase@@EAGJXZ endp
?fv125@FakeDispatcherBase@@EAGJXZ proc
push 125
jmp _DualProcessCommandWrap
?fv125@FakeDispatcherBase@@EAGJXZ endp
?fv126@FakeDispatcherBase@@EAGJXZ proc
push 126
jmp _DualProcessCommandWrap
?fv126@FakeDispatcherBase@@EAGJXZ endp
?fv127@FakeDispatcherBase@@EAGJXZ proc
push 127
jmp _DualProcessCommandWrap
?fv127@FakeDispatcherBase@@EAGJXZ endp
?fv128@FakeDispatcherBase@@EAGJXZ proc
push 128
jmp _DualProcessCommandWrap
?fv128@FakeDispatcherBase@@EAGJXZ endp
?fv129@FakeDispatcherBase@@EAGJXZ proc
push 129
jmp _DualProcessCommandWrap
?fv129@FakeDispatcherBase@@EAGJXZ endp
?fv130@FakeDispatcherBase@@EAGJXZ proc
push 130
jmp _DualProcessCommandWrap
?fv130@FakeDispatcherBase@@EAGJXZ endp
?fv131@FakeDispatcherBase@@EAGJXZ proc
push 131
jmp _DualProcessCommandWrap
?fv131@FakeDispatcherBase@@EAGJXZ endp
?fv132@FakeDispatcherBase@@EAGJXZ proc
push 132
jmp _DualProcessCommandWrap
?fv132@FakeDispatcherBase@@EAGJXZ endp
?fv133@FakeDispatcherBase@@EAGJXZ proc
push 133
jmp _DualProcessCommandWrap
?fv133@FakeDispatcherBase@@EAGJXZ endp
?fv134@FakeDispatcherBase@@EAGJXZ proc
push 134
jmp _DualProcessCommandWrap
?fv134@FakeDispatcherBase@@EAGJXZ endp
?fv135@FakeDispatcherBase@@EAGJXZ proc
push 135
jmp _DualProcessCommandWrap
?fv135@FakeDispatcherBase@@EAGJXZ endp
?fv136@FakeDispatcherBase@@EAGJXZ proc
push 136
jmp _DualProcessCommandWrap
?fv136@FakeDispatcherBase@@EAGJXZ endp
?fv137@FakeDispatcherBase@@EAGJXZ proc
push 137
jmp _DualProcessCommandWrap
?fv137@FakeDispatcherBase@@EAGJXZ endp
?fv138@FakeDispatcherBase@@EAGJXZ proc
push 138
jmp _DualProcessCommandWrap
?fv138@FakeDispatcherBase@@EAGJXZ endp
?fv139@FakeDispatcherBase@@EAGJXZ proc
push 139
jmp _DualProcessCommandWrap
?fv139@FakeDispatcherBase@@EAGJXZ endp
?fv140@FakeDispatcherBase@@EAGJXZ proc
push 140
jmp _DualProcessCommandWrap
?fv140@FakeDispatcherBase@@EAGJXZ endp
?fv141@FakeDispatcherBase@@EAGJXZ proc
push 141
jmp _DualProcessCommandWrap
?fv141@FakeDispatcherBase@@EAGJXZ endp
?fv142@FakeDispatcherBase@@EAGJXZ proc
push 142
jmp _DualProcessCommandWrap
?fv142@FakeDispatcherBase@@EAGJXZ endp
?fv143@FakeDispatcherBase@@EAGJXZ proc
push 143
jmp _DualProcessCommandWrap
?fv143@FakeDispatcherBase@@EAGJXZ endp
?fv144@FakeDispatcherBase@@EAGJXZ proc
push 144
jmp _DualProcessCommandWrap
?fv144@FakeDispatcherBase@@EAGJXZ endp
?fv145@FakeDispatcherBase@@EAGJXZ proc
push 145
jmp _DualProcessCommandWrap
?fv145@FakeDispatcherBase@@EAGJXZ endp
?fv146@FakeDispatcherBase@@EAGJXZ proc
push 146
jmp _DualProcessCommandWrap
?fv146@FakeDispatcherBase@@EAGJXZ endp
?fv147@FakeDispatcherBase@@EAGJXZ proc
push 147
jmp _DualProcessCommandWrap
?fv147@FakeDispatcherBase@@EAGJXZ endp
?fv148@FakeDispatcherBase@@EAGJXZ proc
push 148
jmp _DualProcessCommandWrap
?fv148@FakeDispatcherBase@@EAGJXZ endp
?fv149@FakeDispatcherBase@@EAGJXZ proc
push 149
jmp _DualProcessCommandWrap
?fv149@FakeDispatcherBase@@EAGJXZ endp
?fv150@FakeDispatcherBase@@EAGJXZ proc
push 150
jmp _DualProcessCommandWrap
?fv150@FakeDispatcherBase@@EAGJXZ endp
?fv151@FakeDispatcherBase@@EAGJXZ proc
push 151
jmp _DualProcessCommandWrap
?fv151@FakeDispatcherBase@@EAGJXZ endp
?fv152@FakeDispatcherBase@@EAGJXZ proc
push 152
jmp _DualProcessCommandWrap
?fv152@FakeDispatcherBase@@EAGJXZ endp
?fv153@FakeDispatcherBase@@EAGJXZ proc
push 153
jmp _DualProcessCommandWrap
?fv153@FakeDispatcherBase@@EAGJXZ endp
?fv154@FakeDispatcherBase@@EAGJXZ proc
push 154
jmp _DualProcessCommandWrap
?fv154@FakeDispatcherBase@@EAGJXZ endp
?fv155@FakeDispatcherBase@@EAGJXZ proc
push 155
jmp _DualProcessCommandWrap
?fv155@FakeDispatcherBase@@EAGJXZ endp
?fv156@FakeDispatcherBase@@EAGJXZ proc
push 156
jmp _DualProcessCommandWrap
?fv156@FakeDispatcherBase@@EAGJXZ endp
?fv157@FakeDispatcherBase@@EAGJXZ proc
push 157
jmp _DualProcessCommandWrap
?fv157@FakeDispatcherBase@@EAGJXZ endp
?fv158@FakeDispatcherBase@@EAGJXZ proc
push 158
jmp _DualProcessCommandWrap
?fv158@FakeDispatcherBase@@EAGJXZ endp
?fv159@FakeDispatcherBase@@EAGJXZ proc
push 159
jmp _DualProcessCommandWrap
?fv159@FakeDispatcherBase@@EAGJXZ endp
?fv160@FakeDispatcherBase@@EAGJXZ proc
push 160
jmp _DualProcessCommandWrap
?fv160@FakeDispatcherBase@@EAGJXZ endp
?fv161@FakeDispatcherBase@@EAGJXZ proc
push 161
jmp _DualProcessCommandWrap
?fv161@FakeDispatcherBase@@EAGJXZ endp
?fv162@FakeDispatcherBase@@EAGJXZ proc
push 162
jmp _DualProcessCommandWrap
?fv162@FakeDispatcherBase@@EAGJXZ endp
?fv163@FakeDispatcherBase@@EAGJXZ proc
push 163
jmp _DualProcessCommandWrap
?fv163@FakeDispatcherBase@@EAGJXZ endp
?fv164@FakeDispatcherBase@@EAGJXZ proc
push 164
jmp _DualProcessCommandWrap
?fv164@FakeDispatcherBase@@EAGJXZ endp
?fv165@FakeDispatcherBase@@EAGJXZ proc
push 165
jmp _DualProcessCommandWrap
?fv165@FakeDispatcherBase@@EAGJXZ endp
?fv166@FakeDispatcherBase@@EAGJXZ proc
push 166
jmp _DualProcessCommandWrap
?fv166@FakeDispatcherBase@@EAGJXZ endp
?fv167@FakeDispatcherBase@@EAGJXZ proc
push 167
jmp _DualProcessCommandWrap
?fv167@FakeDispatcherBase@@EAGJXZ endp
?fv168@FakeDispatcherBase@@EAGJXZ proc
push 168
jmp _DualProcessCommandWrap
?fv168@FakeDispatcherBase@@EAGJXZ endp
?fv169@FakeDispatcherBase@@EAGJXZ proc
push 169
jmp _DualProcessCommandWrap
?fv169@FakeDispatcherBase@@EAGJXZ endp
?fv170@FakeDispatcherBase@@EAGJXZ proc
push 170
jmp _DualProcessCommandWrap
?fv170@FakeDispatcherBase@@EAGJXZ endp
?fv171@FakeDispatcherBase@@EAGJXZ proc
push 171
jmp _DualProcessCommandWrap
?fv171@FakeDispatcherBase@@EAGJXZ endp
?fv172@FakeDispatcherBase@@EAGJXZ proc
push 172
jmp _DualProcessCommandWrap
?fv172@FakeDispatcherBase@@EAGJXZ endp
?fv173@FakeDispatcherBase@@EAGJXZ proc
push 173
jmp _DualProcessCommandWrap
?fv173@FakeDispatcherBase@@EAGJXZ endp
?fv174@FakeDispatcherBase@@EAGJXZ proc
push 174
jmp _DualProcessCommandWrap
?fv174@FakeDispatcherBase@@EAGJXZ endp
?fv175@FakeDispatcherBase@@EAGJXZ proc
push 175
jmp _DualProcessCommandWrap
?fv175@FakeDispatcherBase@@EAGJXZ endp
?fv176@FakeDispatcherBase@@EAGJXZ proc
push 176
jmp _DualProcessCommandWrap
?fv176@FakeDispatcherBase@@EAGJXZ endp
?fv177@FakeDispatcherBase@@EAGJXZ proc
push 177
jmp _DualProcessCommandWrap
?fv177@FakeDispatcherBase@@EAGJXZ endp
?fv178@FakeDispatcherBase@@EAGJXZ proc
push 178
jmp _DualProcessCommandWrap
?fv178@FakeDispatcherBase@@EAGJXZ endp
?fv179@FakeDispatcherBase@@EAGJXZ proc
push 179
jmp _DualProcessCommandWrap
?fv179@FakeDispatcherBase@@EAGJXZ endp
?fv180@FakeDispatcherBase@@EAGJXZ proc
push 180
jmp _DualProcessCommandWrap
?fv180@FakeDispatcherBase@@EAGJXZ endp
?fv181@FakeDispatcherBase@@EAGJXZ proc
push 181
jmp _DualProcessCommandWrap
?fv181@FakeDispatcherBase@@EAGJXZ endp
?fv182@FakeDispatcherBase@@EAGJXZ proc
push 182
jmp _DualProcessCommandWrap
?fv182@FakeDispatcherBase@@EAGJXZ endp
?fv183@FakeDispatcherBase@@EAGJXZ proc
push 183
jmp _DualProcessCommandWrap
?fv183@FakeDispatcherBase@@EAGJXZ endp
?fv184@FakeDispatcherBase@@EAGJXZ proc
push 184
jmp _DualProcessCommandWrap
?fv184@FakeDispatcherBase@@EAGJXZ endp
?fv185@FakeDispatcherBase@@EAGJXZ proc
push 185
jmp _DualProcessCommandWrap
?fv185@FakeDispatcherBase@@EAGJXZ endp
?fv186@FakeDispatcherBase@@EAGJXZ proc
push 186
jmp _DualProcessCommandWrap
?fv186@FakeDispatcherBase@@EAGJXZ endp
?fv187@FakeDispatcherBase@@EAGJXZ proc
push 187
jmp _DualProcessCommandWrap
?fv187@FakeDispatcherBase@@EAGJXZ endp
?fv188@FakeDispatcherBase@@EAGJXZ proc
push 188
jmp _DualProcessCommandWrap
?fv188@FakeDispatcherBase@@EAGJXZ endp
?fv189@FakeDispatcherBase@@EAGJXZ proc
push 189
jmp _DualProcessCommandWrap
?fv189@FakeDispatcherBase@@EAGJXZ endp
?fv190@FakeDispatcherBase@@EAGJXZ proc
push 190
jmp _DualProcessCommandWrap
?fv190@FakeDispatcherBase@@EAGJXZ endp
?fv191@FakeDispatcherBase@@EAGJXZ proc
push 191
jmp _DualProcessCommandWrap
?fv191@FakeDispatcherBase@@EAGJXZ endp
?fv192@FakeDispatcherBase@@EAGJXZ proc
push 192
jmp _DualProcessCommandWrap
?fv192@FakeDispatcherBase@@EAGJXZ endp
?fv193@FakeDispatcherBase@@EAGJXZ proc
push 193
jmp _DualProcessCommandWrap
?fv193@FakeDispatcherBase@@EAGJXZ endp
?fv194@FakeDispatcherBase@@EAGJXZ proc
push 194
jmp _DualProcessCommandWrap
?fv194@FakeDispatcherBase@@EAGJXZ endp
?fv195@FakeDispatcherBase@@EAGJXZ proc
push 195
jmp _DualProcessCommandWrap
?fv195@FakeDispatcherBase@@EAGJXZ endp
?fv196@FakeDispatcherBase@@EAGJXZ proc
push 196
jmp _DualProcessCommandWrap
?fv196@FakeDispatcherBase@@EAGJXZ endp
?fv197@FakeDispatcherBase@@EAGJXZ proc
push 197
jmp _DualProcessCommandWrap
?fv197@FakeDispatcherBase@@EAGJXZ endp
?fv198@FakeDispatcherBase@@EAGJXZ proc
push 198
jmp _DualProcessCommandWrap
?fv198@FakeDispatcherBase@@EAGJXZ endp
?fv199@FakeDispatcherBase@@EAGJXZ proc
push 199
jmp _DualProcessCommandWrap
?fv199@FakeDispatcherBase@@EAGJXZ endp
end
| 007slmg-np-activex-justep | ffactivex/FakeDispatcherBase.asm | Assembly | mpl11 | 32,722 |
// stdafx.cpp : source file that includes just the standard includes
// npactivex.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "npactivex.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| 007slmg-np-activex-justep | ffactivex/stdafx.cpp | C++ | mpl11 | 299 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <Windows.h>
#define ATL_THUNK_APIHOOK
EXCEPTION_DISPOSITION
__cdecl
_except_handler(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext );
typedef EXCEPTION_DISPOSITION
(__cdecl *_except_handler_type)(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext );
typedef struct tagATL_THUNK_PATTERN
{
LPBYTE pattern;
int pattern_size;
(void)(*enumerator)(struct _CONTEXT *);
}ATL_THUNK_PATTERN;
void InstallAtlThunkEnumeration();
void UninstallAtlThunkEnumeration(); | 007slmg-np-activex-justep | ffactivex/atlthunk.h | C | mpl11 | 2,219 |
#include "ScriptFunc.h"
NPClass ScriptFunc::npClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ ScriptFunc::_Allocate,
/* deallocate */ ScriptFunc::_Deallocate,
/* invalidate */ NULL,
/* hasMethod */ NULL, //Scriptable::_HasMethod,
/* invoke */ NULL, //Scriptable::_Invoke,
/* invokeDefault */ ScriptFunc::_InvokeDefault,
/* hasProperty */ NULL,
/* getProperty */ NULL,
/* setProperty */ NULL,
/* removeProperty */ NULL,
/* enumerate */ NULL,
/* construct */ NULL
};
map<pair<Scriptable*, MEMBERID>, ScriptFunc*> ScriptFunc::M;
ScriptFunc::ScriptFunc(NPP inst)
{
}
ScriptFunc::~ScriptFunc(void)
{
if (script) {
pair<Scriptable*, MEMBERID> index(script, dispid);
NPNFuncs.releaseobject(script);
M.erase(index);
}
}
ScriptFunc* ScriptFunc::GetFunctionObject(NPP npp, Scriptable *script, MEMBERID dispid) {
pair<Scriptable*, MEMBERID> index(script, dispid);
if (M[index] == NULL) {
ScriptFunc *new_obj = (ScriptFunc*)NPNFuncs.createobject(npp, &npClass);
NPNFuncs.retainobject(script);
new_obj->setControl(script, dispid);
M[index] = new_obj;
} else {
NPNFuncs.retainobject(M[index]);
}
return M[index];
}
bool ScriptFunc::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (!script)
return false;
bool ret = script->InvokeID(dispid, args, argCount, result);
if (!ret) {
np_log(script->instance, 0, "Invoke failed, DISPID 0x%08x", dispid);
}
return ret;
} | 007slmg-np-activex-justep | ffactivex/ScriptFunc.cpp | C++ | mpl11 | 1,507 |
// Copyright qiuc12@gmail.com
// This file is generated autmatically by python. DONT MODIFY IT!
#pragma once
#include <OleAuto.h>
class FakeDispatcher;
HRESULT DualProcessCommand(int commandId, FakeDispatcher *disp, ...);
extern "C" void DualProcessCommandWrap();
class FakeDispatcherBase : public IDispatch {
private:
virtual HRESULT __stdcall fv0();
virtual HRESULT __stdcall fv1();
virtual HRESULT __stdcall fv2();
virtual HRESULT __stdcall fv3();
virtual HRESULT __stdcall fv4();
virtual HRESULT __stdcall fv5();
virtual HRESULT __stdcall fv6();
virtual HRESULT __stdcall fv7();
virtual HRESULT __stdcall fv8();
virtual HRESULT __stdcall fv9();
virtual HRESULT __stdcall fv10();
virtual HRESULT __stdcall fv11();
virtual HRESULT __stdcall fv12();
virtual HRESULT __stdcall fv13();
virtual HRESULT __stdcall fv14();
virtual HRESULT __stdcall fv15();
virtual HRESULT __stdcall fv16();
virtual HRESULT __stdcall fv17();
virtual HRESULT __stdcall fv18();
virtual HRESULT __stdcall fv19();
virtual HRESULT __stdcall fv20();
virtual HRESULT __stdcall fv21();
virtual HRESULT __stdcall fv22();
virtual HRESULT __stdcall fv23();
virtual HRESULT __stdcall fv24();
virtual HRESULT __stdcall fv25();
virtual HRESULT __stdcall fv26();
virtual HRESULT __stdcall fv27();
virtual HRESULT __stdcall fv28();
virtual HRESULT __stdcall fv29();
virtual HRESULT __stdcall fv30();
virtual HRESULT __stdcall fv31();
virtual HRESULT __stdcall fv32();
virtual HRESULT __stdcall fv33();
virtual HRESULT __stdcall fv34();
virtual HRESULT __stdcall fv35();
virtual HRESULT __stdcall fv36();
virtual HRESULT __stdcall fv37();
virtual HRESULT __stdcall fv38();
virtual HRESULT __stdcall fv39();
virtual HRESULT __stdcall fv40();
virtual HRESULT __stdcall fv41();
virtual HRESULT __stdcall fv42();
virtual HRESULT __stdcall fv43();
virtual HRESULT __stdcall fv44();
virtual HRESULT __stdcall fv45();
virtual HRESULT __stdcall fv46();
virtual HRESULT __stdcall fv47();
virtual HRESULT __stdcall fv48();
virtual HRESULT __stdcall fv49();
virtual HRESULT __stdcall fv50();
virtual HRESULT __stdcall fv51();
virtual HRESULT __stdcall fv52();
virtual HRESULT __stdcall fv53();
virtual HRESULT __stdcall fv54();
virtual HRESULT __stdcall fv55();
virtual HRESULT __stdcall fv56();
virtual HRESULT __stdcall fv57();
virtual HRESULT __stdcall fv58();
virtual HRESULT __stdcall fv59();
virtual HRESULT __stdcall fv60();
virtual HRESULT __stdcall fv61();
virtual HRESULT __stdcall fv62();
virtual HRESULT __stdcall fv63();
virtual HRESULT __stdcall fv64();
virtual HRESULT __stdcall fv65();
virtual HRESULT __stdcall fv66();
virtual HRESULT __stdcall fv67();
virtual HRESULT __stdcall fv68();
virtual HRESULT __stdcall fv69();
virtual HRESULT __stdcall fv70();
virtual HRESULT __stdcall fv71();
virtual HRESULT __stdcall fv72();
virtual HRESULT __stdcall fv73();
virtual HRESULT __stdcall fv74();
virtual HRESULT __stdcall fv75();
virtual HRESULT __stdcall fv76();
virtual HRESULT __stdcall fv77();
virtual HRESULT __stdcall fv78();
virtual HRESULT __stdcall fv79();
virtual HRESULT __stdcall fv80();
virtual HRESULT __stdcall fv81();
virtual HRESULT __stdcall fv82();
virtual HRESULT __stdcall fv83();
virtual HRESULT __stdcall fv84();
virtual HRESULT __stdcall fv85();
virtual HRESULT __stdcall fv86();
virtual HRESULT __stdcall fv87();
virtual HRESULT __stdcall fv88();
virtual HRESULT __stdcall fv89();
virtual HRESULT __stdcall fv90();
virtual HRESULT __stdcall fv91();
virtual HRESULT __stdcall fv92();
virtual HRESULT __stdcall fv93();
virtual HRESULT __stdcall fv94();
virtual HRESULT __stdcall fv95();
virtual HRESULT __stdcall fv96();
virtual HRESULT __stdcall fv97();
virtual HRESULT __stdcall fv98();
virtual HRESULT __stdcall fv99();
virtual HRESULT __stdcall fv100();
virtual HRESULT __stdcall fv101();
virtual HRESULT __stdcall fv102();
virtual HRESULT __stdcall fv103();
virtual HRESULT __stdcall fv104();
virtual HRESULT __stdcall fv105();
virtual HRESULT __stdcall fv106();
virtual HRESULT __stdcall fv107();
virtual HRESULT __stdcall fv108();
virtual HRESULT __stdcall fv109();
virtual HRESULT __stdcall fv110();
virtual HRESULT __stdcall fv111();
virtual HRESULT __stdcall fv112();
virtual HRESULT __stdcall fv113();
virtual HRESULT __stdcall fv114();
virtual HRESULT __stdcall fv115();
virtual HRESULT __stdcall fv116();
virtual HRESULT __stdcall fv117();
virtual HRESULT __stdcall fv118();
virtual HRESULT __stdcall fv119();
virtual HRESULT __stdcall fv120();
virtual HRESULT __stdcall fv121();
virtual HRESULT __stdcall fv122();
virtual HRESULT __stdcall fv123();
virtual HRESULT __stdcall fv124();
virtual HRESULT __stdcall fv125();
virtual HRESULT __stdcall fv126();
virtual HRESULT __stdcall fv127();
virtual HRESULT __stdcall fv128();
virtual HRESULT __stdcall fv129();
virtual HRESULT __stdcall fv130();
virtual HRESULT __stdcall fv131();
virtual HRESULT __stdcall fv132();
virtual HRESULT __stdcall fv133();
virtual HRESULT __stdcall fv134();
virtual HRESULT __stdcall fv135();
virtual HRESULT __stdcall fv136();
virtual HRESULT __stdcall fv137();
virtual HRESULT __stdcall fv138();
virtual HRESULT __stdcall fv139();
virtual HRESULT __stdcall fv140();
virtual HRESULT __stdcall fv141();
virtual HRESULT __stdcall fv142();
virtual HRESULT __stdcall fv143();
virtual HRESULT __stdcall fv144();
virtual HRESULT __stdcall fv145();
virtual HRESULT __stdcall fv146();
virtual HRESULT __stdcall fv147();
virtual HRESULT __stdcall fv148();
virtual HRESULT __stdcall fv149();
virtual HRESULT __stdcall fv150();
virtual HRESULT __stdcall fv151();
virtual HRESULT __stdcall fv152();
virtual HRESULT __stdcall fv153();
virtual HRESULT __stdcall fv154();
virtual HRESULT __stdcall fv155();
virtual HRESULT __stdcall fv156();
virtual HRESULT __stdcall fv157();
virtual HRESULT __stdcall fv158();
virtual HRESULT __stdcall fv159();
virtual HRESULT __stdcall fv160();
virtual HRESULT __stdcall fv161();
virtual HRESULT __stdcall fv162();
virtual HRESULT __stdcall fv163();
virtual HRESULT __stdcall fv164();
virtual HRESULT __stdcall fv165();
virtual HRESULT __stdcall fv166();
virtual HRESULT __stdcall fv167();
virtual HRESULT __stdcall fv168();
virtual HRESULT __stdcall fv169();
virtual HRESULT __stdcall fv170();
virtual HRESULT __stdcall fv171();
virtual HRESULT __stdcall fv172();
virtual HRESULT __stdcall fv173();
virtual HRESULT __stdcall fv174();
virtual HRESULT __stdcall fv175();
virtual HRESULT __stdcall fv176();
virtual HRESULT __stdcall fv177();
virtual HRESULT __stdcall fv178();
virtual HRESULT __stdcall fv179();
virtual HRESULT __stdcall fv180();
virtual HRESULT __stdcall fv181();
virtual HRESULT __stdcall fv182();
virtual HRESULT __stdcall fv183();
virtual HRESULT __stdcall fv184();
virtual HRESULT __stdcall fv185();
virtual HRESULT __stdcall fv186();
virtual HRESULT __stdcall fv187();
virtual HRESULT __stdcall fv188();
virtual HRESULT __stdcall fv189();
virtual HRESULT __stdcall fv190();
virtual HRESULT __stdcall fv191();
virtual HRESULT __stdcall fv192();
virtual HRESULT __stdcall fv193();
virtual HRESULT __stdcall fv194();
virtual HRESULT __stdcall fv195();
virtual HRESULT __stdcall fv196();
virtual HRESULT __stdcall fv197();
virtual HRESULT __stdcall fv198();
virtual HRESULT __stdcall fv199();
protected:
const static int kMaxVf = 200;
};
| 007slmg-np-activex-justep | ffactivex/FakeDispatcherBase.h | C++ | mpl11 | 7,671 |
comment ?
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
.386
.model flat
__except_handler proto
.safeseh __except_handler
?
.386
.model flat
PUBLIC __KiUserExceptionDispatcher_hook
.data
public __KiUserExceptionDispatcher_origin
__KiUserExceptionDispatcher_origin dd 0
public __KiUserExceptionDispatcher_ATL_p
__KiUserExceptionDispatcher_ATL_p dd 0
.code
__KiUserExceptionDispatcher_hook proc
; The arguments are already on the stack
call __KiUserExceptionDispatcher_ATL_p
push __KiUserExceptionDispatcher_origin
ret
__KiUserExceptionDispatcher_hook endp
end
| 007slmg-np-activex-justep | ffactivex/atlthunk_asm.asm | Assembly | mpl11 | 2,081 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "npapi.h"
#include <npfunctions.h>
#include <prtypes.h>
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
#include <atlcom.h>
#include <atlctl.h>
#include <varargs.h>
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
//#define NO_REGISTRY_AUTHORIZE
#define np_log(instance, level, message, ...) log_activex_logging(instance, level, __FILE__, __LINE__, message, ##__VA_ARGS__)
// For catch breakpoints.
HRESULT NotImpl();
#define LogNotImplemented(instance) (np_log(instance, 0, "Not Implemented operation!!"), NotImpl())
void
log_activex_logging(NPP instance, unsigned int level, const char* file, int line, char *message, ...);
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved);
NPError NPP_Destroy(NPP instance, NPSavedData **save);
NPError NPP_SetWindow(NPP instance, NPWindow *window);
#define REGISTER_MANAGER | 007slmg-np-activex-justep | ffactivex/npactivex.h | C | mpl11 | 2,994 |
#pragma once
// The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified.
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
| 007slmg-np-activex-justep | ffactivex/targetver.h | C | mpl11 | 1,428 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <npapi.h>
#include <npruntime.h>
#include <map>
#include <vector>
#include "Host.h"
class CAxHost;
class ObjectManager : public CHost
{
public:
ObjectManager(NPP npp2);
~ObjectManager(void);
static NPClass npClass;
CHost* GetPreviousObject(NPP npp);
static ObjectManager* GetManager(NPP npp);
virtual ScriptBase *CreateScriptableObject();
void RetainOwnership(CAxHost *obj);
bool RequestObjectOwnership(NPP newNpp, CAxHost* obj);
private:
struct ScriptManager : public ScriptBase {
ScriptManager(NPP npp) : ScriptBase(npp) {
}
};
std::vector<CHost*> hosts;
std::vector<CHost*> dynamic_hosts;
static NPObject* _Allocate(NPP npp, NPClass *aClass) {
ScriptManager *obj = new ScriptManager(npp);
return obj;
}
static bool Invoke(NPObject *obj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result);
static bool HasMethod(NPObject *obj, NPIdentifier name);
static bool HasProperty(NPObject *obj, NPIdentifier name);
static bool GetProperty(NPObject *obj, NPIdentifier name, NPVariant *value);
static bool SetProperty(NPObject *obj, NPIdentifier name, const NPVariant *value);
static void Deallocate(NPObject *obj);
};
| 007slmg-np-activex-justep | ffactivex/ObjectManager.h | C++ | mpl11 | 2,783 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "oleidl.h"
#include <npapi.h>
#include <npruntime.h>
#include "npactivex.h"
#include "objectProxy.h"
#include "FakeDispatcher.h"
class HTMLDocumentContainer :
public CComObjectRoot,
public IOleContainer,
public IServiceProviderImpl<HTMLDocumentContainer>,
public IWebBrowser2
{
public:
HTMLDocumentContainer();
void Init(NPP instance, ITypeLib *htmlLib);
~HTMLDocumentContainer(void);
// IOleContainer
virtual HRESULT STDMETHODCALLTYPE EnumObjects(
/* [in] */ DWORD grfFlags,
/* [out] */ __RPC__deref_out_opt IEnumUnknown **ppenum) {
return LogNotImplemented(npp);
}
virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(
/* [unique][in] */ __RPC__in_opt IBindCtx *pbc,
/* [in] */ __RPC__in LPOLESTR pszDisplayName,
/* [out] */ __RPC__out ULONG *pchEaten,
/* [out] */ __RPC__deref_out_opt IMoniker **ppmkOut) {
return LogNotImplemented(npp);
}
virtual HRESULT STDMETHODCALLTYPE LockContainer(
/* [in] */ BOOL fLock) {
return LogNotImplemented(npp);
}
// IWebBrowser2
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate2(
/* [in] */ __RPC__in VARIANT *URL,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE QueryStatusWB(
/* [in] */ OLECMDID cmdID,
/* [retval][out] */ __RPC__out OLECMDF *pcmdf) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ExecWB(
/* [in] */ OLECMDID cmdID,
/* [in] */ OLECMDEXECOPT cmdexecopt,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *pvaIn,
/* [unique][optional][out][in] */ __RPC__inout_opt VARIANT *pvaOut) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ShowBrowserBar(
/* [in] */ __RPC__in VARIANT *pvaClsid,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarShow,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarSize) {return LogNotImplemented(npp);};
virtual /* [bindable][propget][id] */ HRESULT STDMETHODCALLTYPE get_ReadyState(
/* [out][retval] */ __RPC__out READYSTATE *plReadyState) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Offline(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbOffline) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Offline(
/* [in] */ VARIANT_BOOL bOffline) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Silent(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbSilent) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Silent(
/* [in] */ VARIANT_BOOL bSilent) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsBrowser(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsBrowser(
/* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsDropTarget(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsDropTarget(
/* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TheaterMode(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_TheaterMode(
/* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_AddressBar(
/* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {*Value = True;return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_AddressBar(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Resizable(
/* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Resizable(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Quit( void) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ClientToWindow(
/* [out][in] */ __RPC__inout int *pcx,
/* [out][in] */ __RPC__inout int *pcy) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE PutProperty(
/* [in] */ __RPC__in BSTR Property,
/* [in] */ VARIANT vtValue) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GetProperty(
/* [in] */ __RPC__in BSTR Property,
/* [retval][out] */ __RPC__out VARIANT *pvtValue) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Name(
/* [retval][out] */ __RPC__deref_out_opt BSTR *Name) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_HWND(
/* [retval][out] */ __RPC__out SHANDLE_PTR *pHWND) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullName(
/* [retval][out] */ __RPC__deref_out_opt BSTR *FullName) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Path(
/* [retval][out] */ __RPC__deref_out_opt BSTR *Path) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Visible(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Visible(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusBar(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusBar(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusText(
/* [retval][out] */ __RPC__deref_out_opt BSTR *StatusText) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusText(
/* [in] */ __RPC__in BSTR StatusText) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_ToolBar(
/* [retval][out] */ __RPC__out int *Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_ToolBar(
/* [in] */ int Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_MenuBar(
/* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_MenuBar(
/* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullScreen(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pbFullScreen) {*pbFullScreen = FALSE; return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_FullScreen(
/* [in] */ VARIANT_BOOL bFullScreen) {return LogNotImplemented(npp);};
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoBack( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoForward( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoHome( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoSearch( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate(
/* [in] */ __RPC__in BSTR URL,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData,
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh2(
/* [unique][optional][in] */ __RPC__in_opt VARIANT *Level) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Stop( void) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Application(
/* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Parent(
/* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Container(
/* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Document(
/* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp);
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TopLevelContainer(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Type(
/* [retval][out] */ __RPC__deref_out_opt BSTR *Type) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Left(
/* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);}
virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Left(
/* [in] */ long Left) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Top(
/* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);}
virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Top(
/* [in] */ long Top) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Width(
/* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);}
virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Width(
/* [in] */ long Width) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Height(
/* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);}
virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Height(
/* [in] */ long Height) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationName(
/* [retval][out] */ __RPC__deref_out_opt BSTR *LocationName) {return LogNotImplemented(npp);}
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationURL(
/* [retval][out] */ __RPC__deref_out_opt BSTR *LocationURL);
virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Busy(
/* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(
/* [out] */ __RPC__out UINT *pctinfo) {return LogNotImplemented(npp);}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) {return LogNotImplemented(npp);}
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(
/* [in] */ __RPC__in REFIID riid,
/* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
/* [range][in] */ __RPC__in_range(0,16384) UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId) {return LogNotImplemented(npp);}
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr) {return LogNotImplemented(npp);}
BEGIN_COM_MAP(HTMLDocumentContainer)
COM_INTERFACE_ENTRY(IOleContainer)
COM_INTERFACE_ENTRY(IServiceProvider)
COM_INTERFACE_ENTRY(IWebBrowser2)
COM_INTERFACE_ENTRY_IID(IID_IWebBrowserApp, IWebBrowser2)
COM_INTERFACE_ENTRY_IID(IID_IWebBrowser, IWebBrowser2)
COM_INTERFACE_ENTRY_AGGREGATE_BLIND(dispatcher)
END_COM_MAP()
static const GUID IID_TopLevelBrowser;
BEGIN_SERVICE_MAP(HTMLDocumentContainer)
SERVICE_ENTRY(IID_IWebBrowserApp)
SERVICE_ENTRY(IID_IWebBrowser2)
SERVICE_ENTRY(IID_IWebBrowser)
SERVICE_ENTRY(SID_SContainerDispatch);
SERVICE_ENTRY(IID_TopLevelBrowser)
END_SERVICE_MAP()
private:
FakeDispatcher *dispatcher;
NPObjectProxy document_;
NPP npp;
};
| 007slmg-np-activex-justep | ffactivex/HTMLDocumentContainer.h | C++ | mpl11 | 17,424 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <atlbase.h>
#include <comdef.h>
#include <npapi.h>
#include <npfunctions.h>
#include <npruntime.h>
#include "variants.h"
#include "FakeDispatcher.h"
#include "Host.h"
extern NPNetscapeFuncs NPNFuncs;
class CAxHost;
struct Scriptable: public ScriptBase
{
private:
Scriptable(const Scriptable &);
// This method iterates all members of the current interface, looking for the member with the
// id of member_id. If not found within this interface, it will iterate all base interfaces
// recursively, until a match is found, or all the hierarchy was searched.
bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind);
DISPID ResolveName(NPIdentifier name, unsigned int invKind);
//bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult);
CComQIPtr<IDispatch> disp;
bool invalid;
DISPID dispid;
void setControl(IUnknown *unk) {
disp = unk;
}
bool IsProperty(DISPID member_id);
public:
Scriptable(NPP npp):
ScriptBase(npp),
invalid(false) {
dispid = -1;
}
~Scriptable() {
}
static NPClass npClass;
static Scriptable* FromIUnknown(NPP npp, IUnknown *unk) {
Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass);
new_obj->setControl(unk);
return new_obj;
}
static Scriptable* FromAxHost(NPP npp, CAxHost* host);
HRESULT getControl(IUnknown **obj) {
if (disp) {
*obj = disp.p;
(*obj)->AddRef();
return S_OK;
}
return E_NOT_SET;
}
void Invalidate() {invalid = true;}
bool HasMethod(NPIdentifier name);
bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result);
bool InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result);
bool HasProperty(NPIdentifier name);
bool GetProperty(NPIdentifier name, NPVariant *result);
bool SetProperty(NPIdentifier name, const NPVariant *value);
bool Enumerate(NPIdentifier **value, uint32_t *count);
private:
// Some wrappers to adapt NPAPI's interface.
static NPObject* _Allocate(NPP npp, NPClass *aClass);
static void _Deallocate(NPObject *obj);
static void _Invalidate(NPObject *obj)
{
if (obj) {
((Scriptable *)obj)->Invalidate();
}
}
static bool _HasMethod(NPObject *npobj, NPIdentifier name) {
return ((Scriptable *)npobj)->HasMethod(name);
}
static bool _Invoke(NPObject *npobj, NPIdentifier name,
const NPVariant *args, uint32_t argCount,
NPVariant *result) {
return ((Scriptable *)npobj)->Invoke(name, args, argCount, result);
}
static bool _HasProperty(NPObject *npobj, NPIdentifier name) {
return ((Scriptable *)npobj)->HasProperty(name);
}
static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) {
return ((Scriptable *)npobj)->GetProperty(name, result);
}
static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) {
return ((Scriptable *)npobj)->SetProperty(name, value);
}
static bool _Enumerate(NPObject *npobj, NPIdentifier **value, uint32_t *count) {
return ((Scriptable *)npobj)->Enumerate(value, count);
}
};
| 007slmg-np-activex-justep | ffactivex/scriptable.h | C++ | mpl11 | 4,934 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <Windows.h>
#include <OleAuto.h>
#include <npapi.h>
#include <npruntime.h>
#include "FakeDispatcherBase.h"
#include "objectProxy.h"
extern ITypeLib *pHtmlLib;
class CAxHost;
EXTERN_C const IID IID_IFakeDispatcher;
class FakeDispatcher :
public FakeDispatcherBase
{
private:
class FakeDispatcherEx: IDispatchEx {
private:
FakeDispatcher *target;
public:
FakeDispatcherEx(FakeDispatcher *target) : target(target) {
}
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
REFIID riid,
__RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) {
return target->QueryInterface(riid, ppvObject);
}
virtual ULONG STDMETHODCALLTYPE AddRef( void) {
return target->AddRef();
}
virtual ULONG STDMETHODCALLTYPE Release( void) {
return target->Release();
}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(
__RPC__out UINT *pctinfo) {
return target->GetTypeInfoCount(pctinfo);
}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(
UINT iTInfo,
LCID lcid,
__RPC__deref_out_opt ITypeInfo **ppTInfo) {
return target->GetTypeInfo(iTInfo, lcid, ppTInfo);
}
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(
__RPC__in REFIID riid,
__RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
__RPC__in_range(0,16384) UINT cNames,
LCID lcid,
__RPC__out_ecount_full(cNames) DISPID *rgDispId) {
return target->GetIDsOfNames(riid, rgszNames, cNames, lcid, rgDispId);
}
virtual HRESULT STDMETHODCALLTYPE Invoke(
DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pDispParams,
VARIANT *pVarResult,
EXCEPINFO *pExcepInfo,
UINT *puArgErr) {
return target->Invoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
virtual HRESULT STDMETHODCALLTYPE GetDispID(
__RPC__in BSTR bstrName,
DWORD grfdex,
__RPC__out DISPID *pid);
virtual HRESULT STDMETHODCALLTYPE InvokeEx(
__in DISPID id,
__in LCID lcid,
__in WORD wFlags,
__in DISPPARAMS *pdp,
__out_opt VARIANT *pvarRes,
__out_opt EXCEPINFO *pei,
__in_opt IServiceProvider *pspCaller);
virtual HRESULT STDMETHODCALLTYPE DeleteMemberByName(
__RPC__in BSTR bstrName,
DWORD grfdex);
virtual HRESULT STDMETHODCALLTYPE DeleteMemberByDispID(DISPID id);
virtual HRESULT STDMETHODCALLTYPE GetMemberProperties(
DISPID id,
DWORD grfdexFetch,
__RPC__out DWORD *pgrfdex);
virtual HRESULT STDMETHODCALLTYPE GetMemberName(
DISPID id,
__RPC__deref_out_opt BSTR *pbstrName);
virtual HRESULT STDMETHODCALLTYPE GetNextDispID(
DWORD grfdex,
DISPID id,
__RPC__out DISPID *pid);
virtual HRESULT STDMETHODCALLTYPE GetNameSpaceParent(
__RPC__deref_out_opt IUnknown **ppunk);
};
public:
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
REFIID riid,
__RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef( void) {
++ref;
return ref;
}
virtual ULONG STDMETHODCALLTYPE Release( void) {
--ref;
if (ref == 0)
delete this;
return ref;
}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(
__RPC__out UINT *pctinfo) {
*pctinfo = 1;
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(
UINT iTInfo,
LCID lcid,
__RPC__deref_out_opt ITypeInfo **ppTInfo);
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(
__RPC__in REFIID riid,
__RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
__RPC__in_range(0,16384) UINT cNames,
LCID lcid,
__RPC__out_ecount_full(cNames) DISPID *rgDispId);
virtual HRESULT STDMETHODCALLTYPE Invoke(
DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pDispParams,
VARIANT *pVarResult,
EXCEPINFO *pExcepInfo,
UINT *puArgErr);
NPObject *getObject() {
return npObject;
}
FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object);
~FakeDispatcher(void);
HRESULT ProcessCommand(int ID, int *parlength,va_list &list);
//friend HRESULT __cdecl DualProcessCommand(int parlength, int commandId, FakeDispatcher *disp, ...);
private:
static ITypeInfo* npTypeInfo;
const static int DISPATCH_VTABLE = 7;
FakeDispatcherEx *extended;
NPP npInstance;
NPObject *npObject;
ITypeLib *typeLib;
ITypeInfo *typeInfo;
CAxHost *internalObj;
bool HasValidTypeInfo();
int ref;
DWORD dualType;
#ifdef DEBUG
char name[50];
char tag[100];
GUID interfaceid;
#endif
UINT FindFuncByVirtualId(int vtbId);
};
| 007slmg-np-activex-justep | ffactivex/FakeDispatcher.h | C++ | mpl11 | 6,240 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <atlstr.h>
#include "npactivex.h"
#include "scriptable.h"
#include "axhost.h"
#include "ObjectManager.h"
#include "FakeDispatcher.h"
// {1DDBD54F-2F8A-4186-972B-2A84FE1135FE}
static const GUID IID_IFakeDispatcher =
{ 0x1ddbd54f, 0x2f8a, 0x4186, { 0x97, 0x2b, 0x2a, 0x84, 0xfe, 0x11, 0x35, 0xfe } };
ITypeInfo* FakeDispatcher::npTypeInfo = (ITypeInfo*)-1;
#define DispatchLog(level, message, ...) np_log(this->npInstance, level, "Disp 0x%08x " message, this, ##__VA_ARGS__)
FakeDispatcher::FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object)
: npInstance(npInstance), typeLib(typeLib), npObject(object), typeInfo(NULL), internalObj(NULL), extended(NULL)
{
ref = 1;
typeLib->AddRef();
NPNFuncs.retainobject(object);
internalObj = (CAxHost*)ObjectManager::GetInternalObject(npInstance, object);
#ifdef DEBUG
name[0] = 0;
tag[0] = 0;
interfaceid = GUID_NULL;
#endif
NPVariantProxy npName, npTag;
ATL::CStringA sname, stag;
NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("id"), &npName);
if (npName.type != NPVariantType_String || npName.value.stringValue.UTF8Length == 0)
NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("name"), &npName);
if (npName.type == NPVariantType_String) {
sname = CStringA(npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length);
#ifdef DEBUG
strncpy(name, npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length);
name[npName.value.stringValue.UTF8Length] = 0;
#endif
}
if (NPNFuncs.hasmethod(npInstance, object, NPNFuncs.getstringidentifier("toString"))) {
NPNFuncs.invoke(npInstance, object, NPNFuncs.getstringidentifier("toString"), &npTag, 0, &npTag);
if (npTag.type == NPVariantType_String) {
stag = CStringA(npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length);
#ifdef DEBUG
strncpy(tag, npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length);
tag[npTag.value.stringValue.UTF8Length] = 0;
#endif
}
}
DispatchLog(1, "Type: %s, Name: %s", stag.GetString(), sname.GetString());
}
/* [local] */ HRESULT STDMETHODCALLTYPE
FakeDispatcher::Invoke(
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr) {
USES_CONVERSION;
// Convert variants
int nArgs = pDispParams->cArgs;
NPVariantProxy *npvars = new NPVariantProxy[nArgs];
for (int i = 0; i < nArgs; ++i) {
Variant2NPVar(&pDispParams->rgvarg[nArgs - 1 - i], &npvars[i], npInstance);
}
// Determine method to call.
HRESULT hr = E_FAIL;
BSTR pBstrName;
NPVariantProxy result;
NPIdentifier identifier = NULL;
NPIdentifier itemIdentifier = NULL;
if (HasValidTypeInfo() && SUCCEEDED(typeInfo->GetDocumentation(dispIdMember, &pBstrName, NULL, NULL, NULL))) {
LPSTR str = OLE2A(pBstrName);
SysFreeString(pBstrName);
DispatchLog(2, "Invoke 0x%08x %d %s", dispIdMember, wFlags, str);
if (dispIdMember == 0x401 && strcmp(str, "url") == 0) {
str = "baseURI";
} else if (dispIdMember == 0x40A && strcmp(str, "parentWindow") == 0) {
str = "defaultView";
}
identifier = NPNFuncs.getstringidentifier(str);
if (dispIdMember == 0 && (wFlags & DISPATCH_METHOD) && strcmp(str, "item") == 0) {
// Item can be evaluated as the default property.
if (NPVARIANT_IS_INT32(npvars[0]))
itemIdentifier = NPNFuncs.getintidentifier(npvars[0].value.intValue);
else if (NPVARIANT_IS_STRING(npvars[0]))
itemIdentifier = NPNFuncs.getstringidentifier(npvars[0].value.stringValue.UTF8Characters);
}
else if (dispIdMember == 0x3E9 && (wFlags & DISPATCH_PROPERTYGET) && strcmp(str, "Script") == 0) {
identifier = NPNFuncs.getstringidentifier("defaultView");
}
}
else if (typeInfo == npTypeInfo && dispIdMember != NULL && dispIdMember != -1) {
identifier = (NPIdentifier) dispIdMember;
}
if (FAILED(hr) && itemIdentifier != NULL) {
if (NPNFuncs.hasproperty(npInstance, npObject, itemIdentifier)) {
if (NPNFuncs.getproperty(npInstance, npObject, itemIdentifier, &result)) {
hr = S_OK;
}
}
}
if (FAILED(hr) && (wFlags & DISPATCH_METHOD)) {
if (NPNFuncs.invoke(npInstance, npObject, identifier, npvars, nArgs, &result)) {
hr = S_OK;
}
}
if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYGET)) {
if (NPNFuncs.hasproperty(npInstance, npObject, identifier)) {
if (NPNFuncs.getproperty(npInstance, npObject, identifier, &result)) {
hr = S_OK;
}
}
}
if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYPUT)) {
if (nArgs == 1 && NPNFuncs.setproperty(npInstance, npObject, identifier, npvars))
hr = S_OK;
}
if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_METHOD)) {
// Call default method.
if (NPNFuncs.invokeDefault(npInstance, npObject, npvars, nArgs, &result)) {
hr = S_OK;
}
}
if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_PROPERTYGET) && pDispParams->cArgs == 0) {
// Return toString()
static NPIdentifier strIdentify = NPNFuncs.getstringidentifier("toString");
if (NPNFuncs.invoke(npInstance, npObject, strIdentify, NULL, 0, &result))
hr = S_OK;
}
if (SUCCEEDED(hr)) {
NPVar2Variant(&result, pVarResult, npInstance);
} else {
DispatchLog(2, "Invoke failed 0x%08x %d", dispIdMember, wFlags);
}
delete [] npvars;
return hr;
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject)
{
HRESULT hr = E_FAIL;
if (riid == IID_IDispatch || riid == IID_IUnknown) {
*ppvObject = this;
AddRef();
hr = S_OK;
} else if (riid == IID_IDispatchEx) {
if (extended == NULL)
extended = new FakeDispatcherEx(this);
*ppvObject = extended;
AddRef();
hr = S_OK;
} else if (riid == IID_IFakeDispatcher) {
*ppvObject = this;
AddRef();
hr = S_OK;
} else if (!typeInfo) {
hr = typeLib->GetTypeInfoOfGuid(riid, &typeInfo);
if (SUCCEEDED(hr)) {
TYPEATTR *attr;
typeInfo->GetTypeAttr(&attr);
dualType = attr->wTypeFlags;
if (!(dualType & TYPEFLAG_FDISPATCHABLE)) {
hr = E_NOINTERFACE;
} else {
*ppvObject = static_cast<FakeDispatcher*>(this);
AddRef();
}
typeInfo->ReleaseTypeAttr(attr);
}
} else {
FakeDispatcher *another_obj = new FakeDispatcher(npInstance, typeLib, npObject);
hr = another_obj->QueryInterface(riid, ppvObject);
another_obj->Release();
}
if (FAILED(hr) && internalObj) {
IUnknown *unk;
internalObj->GetControlUnknown(&unk);
hr = unk->QueryInterface(riid, ppvObject);
unk->Release();
/*
// Try to find the internal object
NPIdentifier object_id = NPNFuncs.getstringidentifier(object_property);
NPVariant npVar;
if (NPNFuncs.getproperty(npInstance, npObject, object_id, &npVar) && npVar.type == NPVariantType_Int32) {
IUnknown *internalObject = (IUnknown*)NPVARIANT_TO_INT32(npVar);
hr = internalObject->QueryInterface(riid, ppvObject);
}*/
}
#ifdef DEBUG
if (hr == S_OK) {
interfaceid = riid;
} else {
// Unsupported Interface!
}
#endif
USES_CONVERSION;
LPOLESTR clsid;
StringFromCLSID(riid, &clsid);
if (FAILED(hr)) {
DispatchLog(0, "Unsupported Interface %s", OLE2A(clsid));
} else {
DispatchLog(0, "QueryInterface %s", OLE2A(clsid));
}
return hr;
}
FakeDispatcher::~FakeDispatcher(void)
{
if (HasValidTypeInfo()) {
typeInfo->Release();
}
if (extended) {
delete extended;
}
NPNFuncs.releaseobject(npObject);
typeLib->Release();
}
// This function is used because the symbol of FakeDispatcher::ProcessCommand is not determined in asm file.
extern "C" HRESULT __cdecl DualProcessCommand(int parlength, int commandId, int returnAddr, FakeDispatcher *disp, ...){
// returnAddr is a placeholder for the calling proc.
va_list va;
va_start(va, disp);
// The parlength is on the stack, the modification will be reflect.
HRESULT ret = disp->ProcessCommand(commandId, &parlength, va);
va_end(va);
return ret;
}
HRESULT FakeDispatcher::GetTypeInfo(
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) {
if (iTInfo == 0 && HasValidTypeInfo()) {
*ppTInfo = typeInfo;
typeInfo->AddRef();
return S_OK;
}
return E_INVALIDARG;
}
HRESULT FakeDispatcher::GetIDsOfNames(
/* [in] */ __RPC__in REFIID riid,
/* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
/* [range][in] */ __RPC__in_range(0,16384) UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId){
if (HasValidTypeInfo()) {
return typeInfo->GetIDsOfNames(rgszNames, cNames, rgDispId);
} else {
USES_CONVERSION;
typeInfo = npTypeInfo;
for (UINT i = 0; i < cNames; ++i) {
DispatchLog(2, "GetIDsOfNames %s", OLE2A(rgszNames[i]));
rgDispId[i] = (DISPID) NPNFuncs.getstringidentifier(OLE2A(rgszNames[i]));
}
return S_OK;
}
}
HRESULT FakeDispatcher::ProcessCommand(int vfid, int *parlength, va_list &args)
{
// This exception is critical if we can't find the size of parameters.
if (!HasValidTypeInfo()) {
DispatchLog(0, "VT interface %d called without type info", vfid);
__asm int 3;
}
UINT index = FindFuncByVirtualId(vfid);
if (index == (UINT)-1) {
DispatchLog(0, "Unknown VT interface id");
__asm int 3;
}
FUNCDESC *func;
// We should count pointer of "this" first.
*parlength = sizeof(LPVOID);
if (FAILED(typeInfo->GetFuncDesc(index, &func)))
__asm int 3;
DISPPARAMS varlist;
// We don't need to clear them.
VARIANT *list = new VARIANT[func->cParams];
varlist.cArgs = func->cParams;
varlist.cNamedArgs = 0;
varlist.rgdispidNamedArgs = NULL;
varlist.rgvarg = list;
// Thanks that there won't be any out variants in HTML.
for (int i = 0; i < func->cParams; ++i) {
int listPos = func->cParams - 1 - i;
ELEMDESC *desc = &func->lprgelemdescParam[listPos];
memset(&list[listPos], 0, sizeof(list[listPos]));
RawTypeToVariant(desc->tdesc, args, &list[listPos]);
size_t varsize = VariantSize(desc->tdesc.vt);
size_t intvarsz = (varsize + sizeof(int) - 1) & (~(sizeof(int) - 1));
args += intvarsz;
*parlength += intvarsz;
}
// We needn't clear it. Caller takes ownership.
VARIANT result;
HRESULT ret = Invoke(func->memid, IID_NULL, NULL, func->invkind, &varlist, &result, NULL, NULL);
if (SUCCEEDED(ret))
ret = ConvertVariantToGivenType(typeInfo, func->elemdescFunc.tdesc, result, args);
size_t varsize = VariantSize(func->elemdescFunc.tdesc.vt);
// It should always be a pointer. It always should be counted.
size_t intvarsz = varsize ? sizeof(LPVOID) : 0;
*parlength += intvarsz;
delete[] list;
return ret;
}
UINT FakeDispatcher::FindFuncByVirtualId(int vtbId) {
if (dualType & TYPEFLAG_FDUAL)
return vtbId + DISPATCH_VTABLE;
else
return vtbId;
}
bool FakeDispatcher::HasValidTypeInfo() {
return typeInfo && typeInfo != npTypeInfo;
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetDispID(
__RPC__in BSTR bstrName,
DWORD grfdex,
__RPC__out DISPID *pid) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::InvokeEx(
__in DISPID id,
__in LCID lcid,
__in WORD wFlags,
__in DISPPARAMS *pdp,
__out_opt VARIANT *pvarRes,
__out_opt EXCEPINFO *pei,
__in_opt IServiceProvider *pspCaller) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByName(
__RPC__in BSTR bstrName,
DWORD grfdex) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByDispID(DISPID id) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberProperties(
DISPID id,
DWORD grfdexFetch,
__RPC__out DWORD *pgrfdex) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberName(
DISPID id,
__RPC__deref_out_opt BSTR *pbstrName) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNextDispID(
DWORD grfdex,
DISPID id,
__RPC__out DISPID *pid) {
return LogNotImplemented(target->npInstance);
}
HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNameSpaceParent(
__RPC__deref_out_opt IUnknown **ppunk) {
return LogNotImplemented(target->npInstance);
}
| 007slmg-np-activex-justep | ffactivex/FakeDispatcher.cpp | C++ | mpl11 | 14,420 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// dllmain.cpp : Defines the entry point for the DLL application.
#include "npactivex.h"
#include "axhost.h"
#include "atlthunk.h"
#include "FakeDispatcher.h"
CComModule _Module;
NPNetscapeFuncs NPNFuncs;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// ==============================
// ! Scriptability related code !
// ==============================
//
// here the plugin is asked by Mozilla to tell if it is scriptable
// we should return a valid interface id and a pointer to
// nsScriptablePeer interface which we should have implemented
// and which should be defined in the corressponding *.xpt file
// in the bin/components folder
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
if(instance == NULL)
return NPERR_GENERIC_ERROR;
CAxHost *host = (CAxHost *)instance->pdata;
if(host == NULL)
return NPERR_GENERIC_ERROR;
switch (variable) {
case NPPVpluginNameString:
*((char **)value) = "ITSTActiveX";
break;
case NPPVpluginDescriptionString:
*((char **)value) = "IT Structures ActiveX for Firefox";
break;
case NPPVpluginScriptableNPObject:
*(NPObject **)value = host->GetScriptableObject();
break;
default:
rv = NPERR_GENERIC_ERROR;
}
return rv;
}
NPError NPP_NewStream(NPP instance,
NPMIMEType type,
NPStream* stream,
NPBool seekable,
uint16* stype)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
int32_t NPP_WriteReady (NPP instance, NPStream *stream)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
int32 rv = 0x0fffffff;
return rv;
}
int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
int32 rv = len;
return rv;
}
NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname)
{
if(instance == NULL)
return;
}
void NPP_Print (NPP instance, NPPrint* printInfo)
{
if(instance == NULL)
return;
}
void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData)
{
if(instance == NULL)
return;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
int16 NPP_HandleEvent(NPP instance, void* event)
{
if(instance == NULL)
return 0;
int16 rv = 0;
CAxHost *host = dynamic_cast<CAxHost*>((CHost *)instance->pdata);
if (host)
rv = host->HandleEvent(event);
return rv;
}
NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
if(pFuncs->size < sizeof(NPPluginFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->setwindow = NPP_SetWindow;
pFuncs->newstream = NPP_NewStream;
pFuncs->destroystream = NPP_DestroyStream;
pFuncs->asfile = NPP_StreamAsFile;
pFuncs->writeready = NPP_WriteReady;
pFuncs->write = NPP_Write;
pFuncs->print = NPP_Print;
pFuncs->event = NPP_HandleEvent;
pFuncs->urlnotify = NPP_URLNotify;
pFuncs->getvalue = NPP_GetValue;
pFuncs->setvalue = NPP_SetValue;
pFuncs->javaClass = NULL;
return NPERR_NO_ERROR;
}
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
/*
* Initialize the plugin. Called the first time the browser comes across a
* MIME Type this plugin is registered to handle.
*/
NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs)
{
#ifdef DEBUG
CString text;
text.Format(_T("NPActiveX Pid %d"), GetCurrentProcessId());
MessageBox(NULL, text, _T(""), MB_OK);
#endif
CoInitialize(NULL);
InstallAtlThunkEnumeration();
if (pHtmlLib == NULL) {
OLECHAR path[MAX_PATH];
GetEnvironmentVariableW(OLESTR("SYSTEMROOT"), path, MAX_PATH - 30);
StrCatW(path, L"\\system32\\mshtml.tlb");
HRESULT hr = LoadTypeLib(path, &pHtmlLib);
}
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
#ifdef NDEF
// The following statements prevented usage of newer Mozilla sources than installed browser at runtime
if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
if(pFuncs->size < sizeof(NPNetscapeFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
#endif
if (!AtlAxWinInit()) {
return NPERR_GENERIC_ERROR;
}
_pAtlModule = &_Module;
memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs));
memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs)));
return NPERR_NO_ERROR;
}
/*
* Shutdown the plugin. Called when no more instanced of this plugin exist and
* the browser wants to unload it.
*/
NPError OSCALL NP_Shutdown(void)
{
AtlAxWinTerm();
UninstallAtlThunkEnumeration();
return NPERR_NO_ERROR;
}
| 007slmg-np-activex-justep | ffactivex/dllmain.cpp | C++ | mpl11 | 7,451 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
struct ITypeInfo;
void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance);
void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance);
size_t VariantSize(VARTYPE vt);
HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest);
void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var); | 007slmg-np-activex-justep | ffactivex/variants.h | C | mpl11 | 2,086 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "scriptable.h"
#include "axhost.h"
#include "ScriptFunc.h"
#include "npactivex.h"
NPClass Scriptable::npClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ Scriptable::_Allocate,
/* deallocate */ Scriptable::_Deallocate,
/* invalidate */ Scriptable::_Invalidate,
/* hasMethod */ Scriptable::_HasMethod,
/* invoke */ Scriptable::_Invoke,
/* invokeDefault */ NULL,
/* hasProperty */ Scriptable::_HasProperty,
/* getProperty */ Scriptable::_GetProperty,
/* setProperty */ Scriptable::_SetProperty,
/* removeProperty */ NULL,
/* enumerate */ Scriptable::_Enumerate,
/* construct */ NULL
};
bool Scriptable::find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) {
bool found = false;
unsigned int i = 0;
FUNCDESC *fDesc;
for (i = 0; (i < attr->cFuncs) && !found; ++i) {
HRESULT hr = info->GetFuncDesc(i, &fDesc);
if (SUCCEEDED(hr)
&& fDesc
&& (fDesc->memid == member_id)) {
if (invKind & fDesc->invkind)
found = true;
}
info->ReleaseFuncDesc(fDesc);
}
if (!found && (invKind & ~INVOKE_FUNC)) {
VARDESC *vDesc;
for (i = 0;
(i < attr->cVars)
&& !found;
++i) {
HRESULT hr = info->GetVarDesc(i, &vDesc);
if ( SUCCEEDED(hr)
&& vDesc
&& (vDesc->memid == member_id)) {
found = true;
}
info->ReleaseVarDesc(vDesc);
}
}
if (!found) {
// iterate inherited interfaces
HREFTYPE refType = NULL;
for (i = 0; (i < attr->cImplTypes) && !found; ++i) {
ITypeInfoPtr baseInfo;
TYPEATTR *baseAttr;
if (FAILED(info->GetRefTypeOfImplType(0, &refType))) {
continue;
}
if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) {
continue;
}
baseInfo->AddRef();
if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) {
continue;
}
found = find_member(baseInfo, baseAttr, member_id, invKind);
baseInfo->ReleaseTypeAttr(baseAttr);
}
}
return found;
}
bool Scriptable::IsProperty(DISPID member_id) {
ITypeInfo *typeinfo;
if (FAILED(disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &typeinfo))) {
return false;
}
TYPEATTR *typeAttr;
typeinfo->GetTypeAttr(&typeAttr);
bool ret = find_member(typeinfo, typeAttr, member_id, DISPATCH_METHOD);
typeinfo->ReleaseTypeAttr(typeAttr);
typeinfo->Release();
return !ret;
}
DISPID Scriptable::ResolveName(NPIdentifier name, unsigned int invKind) {
bool found = false;
DISPID dID = -1;
USES_CONVERSION;
if (!name || !invKind) {
return -1;
}
if (!disp) {
return -1;
}
if (!NPNFuncs.identifierisstring(name)) {
return -1;
}
NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name);
LPOLESTR oleName = A2W(npname);
disp->GetIDsOfNames(IID_NULL, &oleName, 1, 0, &dID);
return dID;
#if 0
int funcInv;
if (FindElementInvKind(disp, dID, &funcInv)) {
if (funcInv & invKind)
return dID;
else
return -1;
} else {
if ((dID != -1) && (invKind & INVOKE_PROPERTYGET)) {
// Try to get property to check.
// Use two parameters. It will definitely fail in property get/set, but it will return other orrer if it's not property.
CComVariant var[2];
DISPPARAMS par = {var, NULL, 2, 0};
CComVariant result;
HRESULT hr = disp->Invoke(dID, IID_NULL, 1, invKind, &par, &result, NULL, NULL);
if (hr == DISP_E_MEMBERNOTFOUND || hr == DISP_E_TYPEMISMATCH)
return -1;
}
}
return dID;
#endif
if (dID != -1) {
ITypeInfoPtr info;
disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info);
if (!info) {
return dID;
}
TYPEATTR *attr;
if (FAILED(info->GetTypeAttr(&attr))) {
return dID;
}
found = find_member(info, attr, dID, invKind);
info->ReleaseTypeAttr(attr);
}
return found ? dID : -1;
}
bool Scriptable::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
np_log(instance, 2, "Invoke %s", NPNFuncs.utf8fromidentifier(name));
DISPID id = ResolveName(name, INVOKE_FUNC);
bool ret = InvokeID(id, args, argCount, result);
if (!ret) {
np_log(instance, 0, "Invoke failed: %s", NPNFuncs.utf8fromidentifier(name));
}
return ret;
}
bool Scriptable::InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (-1 == id) {
return false;
}
CComVariant *vArgs = NULL;
if (argCount) {
vArgs = new CComVariant[argCount];
if (!vArgs) {
return false;
}
for (unsigned int i = 0; i < argCount; ++i) {
// copy the arguments in reverse order
NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance);
}
}
DISPPARAMS params = {NULL, NULL, 0, 0};
params.cArgs = argCount;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = NULL;
params.rgvarg = vArgs;
CComVariant vResult;
HRESULT rc = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, ¶ms, &vResult, NULL, NULL);
if (vArgs) {
delete []vArgs;
}
if (FAILED(rc)) {
np_log(instance, 0, "Invoke failed: 0x%08x, dispid: 0x%08x", rc, id);
return false;
}
Variant2NPVar(&vResult, result, instance);
return true;
}
bool Scriptable::HasMethod(NPIdentifier name) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_FUNC);
return (id != -1) ? true : false;
}
bool Scriptable::HasProperty(NPIdentifier name) {
static NPIdentifier classid = NPNFuncs.getstringidentifier("classid");
static NPIdentifier readyStateId = NPNFuncs.getstringidentifier("readyState");
static NPIdentifier objectId = NPNFuncs.getstringidentifier("object");
static NPIdentifier instanceId = NPNFuncs.getstringidentifier("__npp_instance__");
if (name == classid || name == readyStateId || name == instanceId || name == objectId) {
return true;
}
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT);
return (id != -1) ? true : false;
}
bool Scriptable::GetProperty(NPIdentifier name, NPVariant *result) {
if (invalid)
return false;
static NPIdentifier classid = NPNFuncs.getstringidentifier("classid");
static NPIdentifier readyStateId = NPNFuncs.getstringidentifier("readyState");
static NPIdentifier objectId = NPNFuncs.getstringidentifier("object");
static NPIdentifier instanceId = NPNFuncs.getstringidentifier("__npp_instance__");
if (name == classid) {
CAxHost *host = (CAxHost*)this->host;
if (this->disp == NULL) {
char* cstr = (char*)NPNFuncs.memalloc(1);
cstr[0] = 0;
STRINGZ_TO_NPVARIANT(cstr, *result);
return true;
} else {
USES_CONVERSION;
char* cstr = (char*)NPNFuncs.memalloc(50);
strcpy(cstr, "CLSID:");
LPOLESTR clsidstr;
StringFromCLSID(host->getClsID(), &clsidstr);
// Remove braces.
clsidstr[lstrlenW(clsidstr) - 1] = '\0';
strcat(cstr, OLE2A(clsidstr + 1));
CoTaskMemFree(clsidstr);
STRINGZ_TO_NPVARIANT(cstr, *result);
return true;
}
} else if (name == readyStateId) {
INT32_TO_NPVARIANT(4, *result);
return true;
} else if (name == instanceId) {
INT32_TO_NPVARIANT((int32)instance, *result);
return true;
} else if (name == objectId) {
OBJECT_TO_NPVARIANT(this, *result);
NPNFuncs.retainobject(this);
return true;
}
DISPID id = ResolveName(name, INVOKE_PROPERTYGET);
if (-1 == id) {
np_log(instance, 0, "Cannot find property: %s", NPNFuncs.utf8fromidentifier(name));
return false;
}
DISPPARAMS params;
params.cArgs = 0;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = NULL;
params.rgvarg = NULL;
CComVariant vResult;
if (IsProperty(id)) {
HRESULT hr = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, ¶ms, &vResult, NULL, NULL);
if (SUCCEEDED(hr)) {
Variant2NPVar(&vResult, result, instance);
np_log(instance, 2, "GetProperty %s", NPNFuncs.utf8fromidentifier(name));
return true;
}
}
np_log(instance, 2, "GetMethodObject %s", NPNFuncs.utf8fromidentifier(name));
OBJECT_TO_NPVARIANT(ScriptFunc::GetFunctionObject(instance, this, id), *result);
return true;
}
bool Scriptable::SetProperty(NPIdentifier name, const NPVariant *value) {
static NPIdentifier classid = NPNFuncs.getstringidentifier("classid");
if (name == classid) {
np_log(instance, 1, "Set classid property: %s", value->value.stringValue);
CAxHost* axhost = (CAxHost*)host;
CLSID newCLSID = CAxHost::ParseCLSIDFromSetting(value->value.stringValue.UTF8Characters, value->value.stringValue.UTF8Length);
if (newCLSID != GUID_NULL && (!axhost->hasValidClsID() || newCLSID != axhost->getClsID())) {
axhost->Clear();
if (axhost->setClsID(newCLSID)) {
axhost->CreateControl(false);
IUnknown *unk;
if (SUCCEEDED(axhost->GetControlUnknown(&unk))) {
this->setControl(unk);
unk->Release();
}
axhost->ResetWindow();
}
}
return true;
}
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYPUT);
if (-1 == id) {
return false;
}
CComVariant val;
NPVar2Variant(value, &val, instance);
DISPPARAMS params;
// Special initialization needed when using propery put.
DISPID dispidNamed = DISPID_PROPERTYPUT;
params.cNamedArgs = 1;
params.rgdispidNamedArgs = &dispidNamed;
params.cArgs = 1;
params.rgvarg = &val;
CComVariant vResult;
WORD wFlags = DISPATCH_PROPERTYPUT;
if (val.vt == VT_DISPATCH) {
wFlags |= DISPATCH_PROPERTYPUTREF;
}
const char* pname = NPNFuncs.utf8fromidentifier(name);
if (FAILED(disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, ¶ms, &vResult, NULL, NULL))) {
np_log(instance, 0, "SetProperty failed %s", pname);
return false;
}
np_log(instance, 0, "SetProperty %s", pname);
return true;
}
Scriptable* Scriptable::FromAxHost(NPP npp, CAxHost* host)
{
Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass);
IUnknown *unk;
if (SUCCEEDED(host->GetControlUnknown(&unk))) {
new_obj->setControl(unk);
new_obj->host = host;
unk->Release();
}
return new_obj;
}
NPObject* Scriptable::_Allocate(NPP npp, NPClass *aClass)
{
return new Scriptable(npp);
}
void Scriptable::_Deallocate(NPObject *obj) {
if (obj) {
Scriptable *a = static_cast<Scriptable*>(obj);
//np_log(a->instance, 3, "Dealocate obj");
delete a;
}
}
bool Scriptable::Enumerate(NPIdentifier **value, uint32_t *count) {
UINT cnt;
if (!disp || FAILED(disp->GetTypeInfoCount(&cnt)))
return false;
*count = 0;
for (UINT i = 0; i < cnt; ++i) {
CComPtr<ITypeInfo> info;
disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info);
TYPEATTR *attr;
info->GetTypeAttr(&attr);
*count += attr->cFuncs;
info->ReleaseTypeAttr(attr);
}
uint32_t pos = 0;
NPIdentifier *v = (NPIdentifier*) NPNFuncs.memalloc(sizeof(NPIdentifier) * *count);
USES_CONVERSION;
for (UINT i = 0; i < cnt; ++i) {
CComPtr<ITypeInfo> info;
disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info);
TYPEATTR *attr;
info->GetTypeAttr(&attr);
BSTR name;
for (uint j = 0; j < attr->cFuncs; ++j) {
FUNCDESC *desc;
info->GetFuncDesc(j, &desc);
if (SUCCEEDED(info->GetDocumentation(desc->memid, &name, NULL, NULL, NULL))) {
LPCSTR str = OLE2A(name);
v[pos++] = NPNFuncs.getstringidentifier(str);
SysFreeString(name);
}
info->ReleaseFuncDesc(desc);
}
info->ReleaseTypeAttr(attr);
}
*count = pos;
*value = v;
return true;
} | 007slmg-np-activex-justep | ffactivex/scriptable.cpp | C++ | mpl11 | 13,344 |